Mass Delete Records Across Modules

Mass Delete Records Across Modules

Season's greetings to our coding enthusiasts! 

Let us code our way into the festive spirit with another insightful post in our Kaizen series!

In this post, we will explore the process of creating a custom button using functions on the records' detail page. This enables the deletion of all associated child records when the current record is deleted. To fulfill this requirement, we will leverage APIs like COQL API, Records API, and Mass Delete API.

Currently, Zoho CRM provides the delete action exclusively for a specific related list modules when the parent record is deleted. Here are the specifics of ZOHO CRM's default support for deleting related list modules:

Record Module
Related List Module
Leads
Activities, Visits and Email Drafts
ContactsActivities, Visits, Appointments and Email Drafts
Accounts
Activities, Contacts, Deals, Quotes, Sales Orders, Invoices, Cases, Appointments and Email Drafts
Deals
Activities, Cases, Competitors and Email Drafts
Campaigns
Activities, Email Drafts and Child Campaigns 
Cases
Activities and Email Drafts
Products
Activities, Solutions, Cases and Email Drafts
Vendors
Activities and Email Drafts
Quotes
Activities and Email Drafts
Sales Orders
Activities and Email Drafts
Purchase Orders
Activities and Email Drafts
Invoices
Activities and Email Drafts
Services
Appointments and Email Drafts
Custom
Activities and Email Drafts

Perform Mass Delete Across Modules

Assume that you are the Manager of Zylker, an educational institution utilizing ZOHO CRM for customer relationship management. You have implemented custom modules, namely Training Program and Participants in your organization. 

Now, you aim to streamline record management by creating a custom button on the Training Program module's records detail page. On triggering, this button should delete all associated participants of a specific program along with the program itself. 

Let us guide you through the step-by-step process of fulfilling this requirement using ZOHO CRM functions.

Prerequisites

Achieving this requirement is versatile, applicable to both records with a single child module as well as records with multiple child modules. 

A lookup field serves to establish a connection between two modules, designating the module where the lookup field is employed as the child module. The module that the lookup field points to is referred to as the parent module.

To keep it simple, let us consider Participants as the child module with a lookup relationship to the Training Program parent module. 

The knowledge of COQL, Records and Mass Delete Records APIs, Deluge Script and ZOHO CRM Functions ensure effective execution of our outlined process.

Creating a Custom Button

Step 1: Begin by navigating to Setup > Customization > Modules and Fields > Training Program > Links and Buttons > New Button within your ZOHO CRM interface.

Step 2: Provide a name and description for the button. Next, select the Details Page as the designated location for the button from the drop-down menu.



Refer to this document to learn more on creating and using custom buttons.

Step 3: Configure the button's action by selecting Writing Function from the menu.



Step 4: Fill in the basic details for creating a new function. 

Step 5: After clicking the create button, you will be directed to an editor interface, as depicted in this image.



You have to code your function logic in this editor and click the Save button on the top right corner. 

For the scenario discussed, we have attached the function code in a zip file with this post. Download and explore the code to gain hands-on experience in this use case. 

Step 6: Next, you will be redirected to the Links and Buttons page, where you need to configure the visibility of the button based on profiles. Afterward, click on the Save button to confirm your settings.


Flow of the function

The function should initially make a COQL API call to retrieve the participant records that correspond to the record ID of the training program from which the button is triggered. This API can fetch up to 2000 related child records in a single API call.

queryMap = Map();
queryMap.put("select_query","select id from Participants where Training_Program =" + id + "Limit 2000");
response = invokeurl
[
type :POST
parameters:queryMap.toString()
connection:"crm_oauth_connection"
];

Here, connections are used to make ZOHO CRM API calls. To get the current record ID, you have to configure it in function arguments. 

Click Edit Arguments from the top of the page and associate the Training Program ID as shown in this image. 



Before proceeding to the next step, it's crucial to be aware of the following constraints associated with the APIs:
  • COQL API: It can retrieve a maximum of 2000 records per API call.
  • Delete Records API: It has the capability to delete up to 100 records in a single API call.
  • Mass Delete Records API: By utilizing record IDs, it can delete a maximum of 500 records per API call.
Given these constraints, the following logic has been devised to address our specified requirement:

--->  If the participant count is 0, the system should proceed to delete the current record exclusively. 
--->  Incases where the record count is below 100, the Delete Record API must be employed to eliminate records from the Participants module.
--->  If the participant count exceeds 100, the Mass Delete Records API should be used for deleting records within the child module. For scenarios where more than 500 records need deletion, it is necessary to execute this in a loop for four iterations with each deleting 500 records.

Let us execute this logic in Deluge script,

if(!isNull(response))
{
response = response.toMap();
count = response.getJSON("info").get("count").toNumber();
has_more = response.getJSON("info").get("more_records");
id_list = List();
itr_list = {0,1,2,3};
response = response.getJSON("data");
result = List();
if(count > 0)
{
for each  item in response
{
id_list.add(item.getJSON("id"));
}
if(count > 100)
{
end = 0;
start = 0;
for each  itr in itr_list
{
if(count / 500 - itr > 0)
{
idMap = Map();
if(count - end > 500)
{
end = end + 500;
}
else
{
end = count;
}
idMap.put("ids",id_list.subList(start,end));
response = invokeurl
[
type :POST
parameters:idMap.toString()
connection:"crm_oauth_connection"
];
start = end;
}
}
}
else
{
response = invokeurl
[
type :DELETE
connection:"crm_oauth_connection"
];
}
}
}

Now, let us address the scenario of a training program with over 2000 participants. Following the logic outlined above, our custom button will handle the deletion of only 2000 records. 

To manage this, after successfully deleting the initial 2000 records, the record from the Training Program module should not be deleted. Here, we have to configure a pop-up message signaling that additional records require deletion. To proceed, users must click the same button to eliminate the remaining records along with the current one.

After deleting all records from the child modules, the custom button will proceed to remove the current Training Program record, as shown in the following Deluge code.

if(isNull(response) || !has_more)
{
response = invokeurl
[
type :DELETE
connection:"crm_oauth_connection"
];
return "Deleted Successfully";
}
return "Over 2000 related records were detected. Click 'Cascade Delete' again to delete the remaining and this training program. ";

Let us now check our custom button from the details page of the Training Programs module. 



To prevent additional clicks for deleting the remaining records, we will circle back to you on next Friday with a solution that incorporates the looping mechanism. 
 
We have also brought you a wave of innovation and enhanced features in our V6 APIs. Take a look at them and empower your coding journey with us. 

If you have any queries, feel free to drop them in the comments section below or reach out to us directly at support@zohocrm.com. We eagerly await your thoughts and feedback on this!

Cheers to a productive and joyful season!


    Access your files securely from anywhere







                            Zoho Developer Community





                                                  Use cases

                                                  Make the most of Zoho Desk with the use cases.

                                                   
                                                    

                                                  eBooks

                                                  Download free eBooks and access a range of topics to get deeper insight on successfully using Zoho Desk.

                                                   
                                                    

                                                  Videos

                                                  Watch comprehensive videos on features and other important topics that will help you master Zoho Desk.

                                                   
                                                    

                                                  Webinar

                                                  Sign up for our webinars and learn the Zoho Desk basics, from customization to automation and more

                                                   
                                                    
                                                  • Desk Community Learning Series


                                                  • Meetups


                                                  • Ask the Experts


                                                  • Kbase


                                                  • Resources


                                                  • Glossary


                                                  • Desk Marketplace


                                                  • MVP Corner




                                                            • Sticky Posts

                                                            • Kaizen #197: Frequently Asked Questions on GraphQL APIs

                                                              🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
                                                            • Kaizen #198: Using Client Script for Custom Validation in Blueprint

                                                              Nearing 200th Kaizen Post – 1 More to the Big Two-Oh-Oh! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
                                                            • Celebrating 200 posts of Kaizen! Share your ideas for the milestone post

                                                              Hello Developers, We launched the Kaizen series in 2019 to share helpful content to support your Zoho CRM development journey. Staying true to its spirit—Kaizen Series: Continuous Improvement for Developer Experience—we've shared everything from FAQs
                                                            • Kaizen #193: Creating different fields in Zoho CRM through API

                                                              🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
                                                            • Client Script | Update - Introducing Commands in Client Script!

                                                              Have you ever wished you could trigger Client Script from contexts other than just the supported pages and events? Have you ever wanted to leverage the advantage of Client Script at your finger tip? Discover the power of Client Script - Commands! Commands


                                                            Manage your brands on social media



                                                                  Zoho TeamInbox Resources



                                                                      Zoho CRM Plus Resources

                                                                        Zoho Books Resources


                                                                          Zoho Subscriptions Resources

                                                                            Zoho Projects Resources


                                                                              Zoho Sprints Resources


                                                                                Qntrl Resources


                                                                                  Zoho Creator Resources



                                                                                      Zoho CRM Resources

                                                                                      • CRM Community Learning Series

                                                                                        CRM Community Learning Series


                                                                                      • Kaizen

                                                                                        Kaizen

                                                                                      • Functions

                                                                                        Functions

                                                                                      • Meetups

                                                                                        Meetups

                                                                                      • Kbase

                                                                                        Kbase

                                                                                      • Resources

                                                                                        Resources

                                                                                      • Digest

                                                                                        Digest

                                                                                      • CRM Marketplace

                                                                                        CRM Marketplace

                                                                                      • MVP Corner

                                                                                        MVP Corner







                                                                                          Design. Discuss. Deliver.

                                                                                          Create visually engaging stories with Zoho Show.

                                                                                          Get Started Now


                                                                                            Zoho Show Resources


                                                                                              Zoho Writer Writer

                                                                                              Get Started. Write Away!

                                                                                              Writer is a powerful online word processor, designed for collaborative work.

                                                                                                Zoho CRM コンテンツ








                                                                                                  Nederlandse Hulpbronnen


                                                                                                      ご検討中の方




                                                                                                            • Recent Topics

                                                                                                            • Add the ability to view number of hours planned for a workorder while in the Dispatch Console

                                                                                                              Hi Zoho, When dispatching a work order through the Dispatch Console, there's currently no way to view the number of planned hours for the service tasks associated with that specific work order. Having to click into the details each time to check planned
                                                                                                            • Uploading Files from uploads api

                                                                                                              I tried uploading the image from the API call but its giving me unauthorized error even i have given valid token in header. After uploading i need that id to pass in create ticket api uploads but its not uploading that file. Please help me out in th
                                                                                                            • Categorize Items with Item Headers

                                                                                                              Hello customers, Did you ever want to classify items based on specific categories to help your customers understand your invoice better? With the new Item Header feature, you can easily categorize items in your invoices and estimates and give them a common title.  Item Headers are available in the Invoices, the Recurring Invoices and the Estimates module. It can be carried forward from estimates to invoices at the time of converting the estimates.  To add an item header: Go to the Estimates, Invoices
                                                                                                            • URLs being masked despite disabling tracking

                                                                                                              Hey, We had disabled click tracking from an email update we are sharing with our users. Despite this, the URL the end user is receiving is masked, and looks like "https://qksyl-cmpzourl.maillist-manage.net/click/1d8e72714515cda6/1d8e72714515ca70" instead
                                                                                                            • Change format of quantity format

                                                                                                              Hi,  I would like to change the qunatity format from 1,00 to 1.  Is this possible?   thanks!
                                                                                                            • square up and Zoho books

                                                                                                              Since we set up the app connection between square up and Zoho books we have realised that when the amounts are getting transferred Zoho is adding VAT again making the numbers 20% more than they should be. We have checked our settings and they VAT/ Tax
                                                                                                            • How to provide Access rights to specific Bank accounts

                                                                                                              We have several bank accounts. I want to provide certain members access to only 2-3 accounts. It appears that when I give permissions, they are for ALL bank accounts. How do I do that?
                                                                                                            • Errors Getting a Bank Transaction

                                                                                                              Using Postman(for testing), I am receiving errors when attempting to get a single bank transaction. I am able to receive the list of bank transactions with https://www.zohoapis.com/books/v3/banktransactions/?organization_id={org_id} but when I try to
                                                                                                            • Subscriptions Plans and CRM Products Integration?

                                                                                                              Is there any way to set up plans and pricing in Zoho Subscriptions and have those available as Products in the CRM? We are trying to set up the CRM and the Products seem to be more geared toward selling products that are not subscription based.  So if we sell annual or monthly contracts which are $10/seat/month, I can set this up as a plan in Subscriptions, but how can I set the same thing up in the CRM for the salespeople to sell/quote? What is the best practice for setting up the CRM Products to
                                                                                                            • Mapping Zoho Subscription Plans and Products to CRM and Books

                                                                                                              We have products that are one time products and subscription products.   1) We would like to have the ability to create an opportunity in CRM that includes both one-time charge products and subscription products.  Currently the only way of creating a subscription product is by defining a "Product->Plan" hierarchy in Zoho Subscription.  It appears that the only SYNC between Subscription and CRM is around contacts and the Product->Plan hierarchy doesn't sync to CRM, thus, you would need a duplicate
                                                                                                            • Zoho People Attendance Module - Split Shifts

                                                                                                              Hello, Our business employs a number of college students who often split their workdays between work hours and class schedules, resulting in split shifts. For example: Employee 1 works 9am to 11:30am and then leaves for class, returning to work at 3pm
                                                                                                            • Bulk update fields based on date

                                                                                                              Hi! I need all the quotes with "Quote Stage" set to "Next Year" to update to "Draft" every January 8 (every year). Can you help?
                                                                                                            • Target for a campaign

                                                                                                              Hi, Hope you can help me. I need to create a report (for a marketing campaign) that combines Deals and Contacts to export all the contacts with closed deals. I can easily do that, what I cannot do is to remove from the target the contacts that have more
                                                                                                            • Zoho Desk + Jira integration - Email notifications and comments posted by administrator instead of real user

                                                                                                              Dear All, I set up the integration under my admin account, and now when users leave comments in Jira (to created tickets in Zoho Desk), the email notifications show that the ‘Administrator’ left a comment, not a real user. The same happens in the ticket
                                                                                                            • Celebrating the power of visuals

                                                                                                              On World Photography Day, we would like to highlight the power of visuals in customer service. Visuals promote learning and understanding in less time. A photograph can rekindle a memory, convey more than words, and give a fresh perspective. How does
                                                                                                            • Customer address in Zoho Bookings

                                                                                                              Hello,  Is it possible to add customer address information to the Zoho bookings appointment screen? Or have it pull that information automatically from the CRM? We are wanting to use this as a field management software but it is difficult to pull the address from multiple sources when it would be ideal to have a clickable address on the appointment screen that opens up the user's maps.  It would also be advantageous for the "list view" to show appointment times instead of just duration and booking
                                                                                                            • Blocking / black listing customers

                                                                                                              Hi, We have a situation, we observed that certain customers are blocking multiple appointments with our advsiors but not showing up. Some of these are repeat offenders. This leads to those service hours getting blocked and not available for genuine customers.
                                                                                                            • Option to block bookings from specific email address or ip adresss in zoho booking

                                                                                                              Sometime few of our client keep booking irrelevant booking service just to resolve their queries and they keep booking it again and again whenever they have queries. Currently its disturbing our current communication process and hierarchy which we have
                                                                                                            • Feature Request: Email Templates for notifications accross all services

                                                                                                              Currently in Zoho Bookings, email notifications (such as booking confirmations, reminders, and cancellations) must be customized individually for each service. This becomes time-consuming and error-prone when managing multiple services that require consistent
                                                                                                            • Allow customers to choose meeting venue and meeting duration on booking page

                                                                                                              My business primarily involves one-to-one meetings with my clients. Given the hybrid-work world we now find ourselves in, these meetings can take several forms (which I think of as the meeting "venue"): In-person Zoom Phone call I currently handle these
                                                                                                            • Approval-based booking with Zoho Creator and Zoho Bookings

                                                                                                              Hi community members, We have developed a workaround for approval-based booking using Zoho Creator and Zoho Bookings! This provides a temporary solution as we work on the native feature, and it's useful for anyone needing an approval workflow when confirming
                                                                                                            • Member Accounts in Related List

                                                                                                              Hi Team, Currently, when a parent account is associated with an account in FSM, there is no related list displaying the associated member accounts under the parent account’s related list section. To view member accounts, I have to manually search using
                                                                                                            • how do i remove a specific Zoho Service from my account

                                                                                                              I no longer need Zoho CRM, ZRM Assist nor ZRM BugTracker. How do I remove them from the list of apps for my account?
                                                                                                            • I Want migarte all invoice details to zoho sheets

                                                                                                              I want to migrate all existing invoice details to Zoho Sheet, and automatically update the sheet whenever a new invoice is created.
                                                                                                            • were can i find my invoices i need this for my accountant

                                                                                                              were can i find my invoices i need this for my accountant, how can i get id direct to my email?
                                                                                                            • ONLY email field not populating Writer fillable document (randomly)

                                                                                                              I have a Zoho Writer fillable document that has pulled all my data from my Zoho Sheets file, EXCEPT the email column. It pulled every data before and after that column with no issues. Screenshots attached. It's not my first time using the app or the feature,
                                                                                                            • My number is marked as spam

                                                                                                              Hello Zoho Mail Support, My phone number was incorrectly flagged as “spam” during sign-up. This is my personal number, and I have not engaged in any spam activities. Kindly review and verify my account so I can proceed with my email setup. Thanks.
                                                                                                            • Personnalisation des paramètres dans Zoho Mail

                                                                                                              Pourquoi cela compte-t-il ? La personnalisation des paramètres dans Zoho Mail permet aux administrateurs de configurer l’environnement de messagerie en fonction des besoins spécifiques de leur organisation. Que ce soit pour alléger l’interface pour certaines
                                                                                                            • How To Save Data Into Zoho CRM Sandbox

                                                                                                              Hi Community, I want to save data into my zoho sandbox , for this I am using this api endpoint - https://www.zohoapis.com/crm/v8/Patients but I am getting this error - { "success": false, "message": "Zoho API request failed", "error": { "code": "INVALID_MODULE",
                                                                                                            • Automate pushing Zoho CRM backups into Zoho WorkDrive

                                                                                                              Through our Zoho One subscription we have both Zoho CRM and Zoho WorkDrive. We have regular backups setup in Zoho CRM. Once the backup is created, we are notified. Since we want to keep these backups for more than 7 days, we manually download them. They
                                                                                                            • Question about retrieving unsubscribed contacts (outside of lists) via API

                                                                                                              Hello, I am currently using Zoho Marketing Automation and would like to integrate it with our company’s core system. For this purpose, I am exploring the API options available to retrieve contact information. Specifically, I would like to know if there
                                                                                                            • Getting “mandatory field missing: Service_Line_Items” When Creating Work Order via Zoho Flow Deluge

                                                                                                              Hi Team, I’m trying to create a Work Order in Zoho FSM with only a Service Line Item (no Parts). However, I keep getting this error: Work Order Response: {"code":"MANDATORY_NOT_FOUND","details":{"api_name":"Service_Line_Items"},"message":"required field
                                                                                                            • How to customize the colors of the Client Portal login screen and add the company logo?

                                                                                                              As title, how to customize the colors of the Client Portal login screen and add the company logo?
                                                                                                            • Daily updates/fixes and how to see what was changed?

                                                                                                              When I receive the notification that zoho was updated and I need to refresh it. How can I see what was changed or fixed? Sometimes they change things that effect my books and I need to know what they did. For example over this past weekend something was
                                                                                                            • Upcoming Change: Snowflake Username/Password Authentication Deprecation – Action Required

                                                                                                              Hello Users, Snowflake has officially announced that username and password-based authentication will be deprecated by November 2025. You can find the official announcement [here]. If you're using a Snowflake connection in Zoho Analytics to import data,
                                                                                                            • Why should I choose Zoho Inventory vs Odoo?

                                                                                                              Hello there! I have used Zoho in different companies I've worked in, and I have a positive perception of it. I am starting a new import business for pipes, tubes, fittings, valves, elbows, etc., which all have serial numbers, cast numbers, etc., so I
                                                                                                            • Product Updates in Zoho Workplace applications | July 2025

                                                                                                              Hello Workplace Community, Let’s take a look at the new features and enhancements that went live across all Workplace applications this July. Zoho Mail Import bookmarks from Pocket Worried about losing your Pocket bookmarks? Don't worry we have got you.
                                                                                                            • PLEASE FIX YOR BUGS

                                                                                                              PICTURES ARE BEING REJECTED DESPITE THEM FOLLOWING THE GUIDELINES ON DIMENTIONS.
                                                                                                            • Kaizen# 204 - Answering Your Questions | Perform Field Updates before Blueprint transition via Client Script

                                                                                                              Hello everyone! Welcome back to another exciting Kaizen post. One of the questions we received through your Kaizen feedback was: “How can I update fields before Blueprint transition and how to prevent a transition based on a condition using Client Script?”
                                                                                                            • Create online meetings for Booking Pages with Zoho Meetings and Zoom

                                                                                                              Greetings, We hope you're all doing well. We're excited to share some recent enhancements to Bigin's Booking Pages. As you know, Booking Pages let you create public pages to share your availability so that your customers can easily book time slots with
                                                                                                            • Next Page