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

                                                                                                            • Upcoming Changes to LinkedIn Parsing in Resume Extractor

                                                                                                              Starting 31 July 2025, the Zoho Recruit Resume Extractor will no longer support direct parsing of candidate data from LinkedIn profiles. Why Is This Change Needed? In accordance with LinkedIn’s platform policies, extracting profile data through browser
                                                                                                            • Is there a way to map complex product variants from Magento into Zoho CRM without losing SKU-level details?

                                                                                                              Hi everyone, I’m working on a Magento-based store that uses highly detailed product variants, and I’m struggling to map them into Zoho CRM without losing SKU-level details. The problem is that variants often collapse into single entries, which affects
                                                                                                            • how to create view in leads module to that will show all leads + converted leads?

                                                                                                              is it possible to make custom view that combine all leads + converted leads? how to do that
                                                                                                            • Deal Stage component/widget/whatever it is... event

                                                                                                              Deal Stages I am trying to access the event and value of this component. I can do it by changing the Stage field but users can also change a Deal Stage via this component and I need to be able to capture both values. Clicking on 'Verbal' for instance,
                                                                                                            • Reply and react to comments

                                                                                                              Hi everyone! We're excited to bring to you a couple of new features that'll make your sprint process simpler. A cloud application brings with it an array of social media features that can be efficiently used in your organizational setup. As an agile scrum
                                                                                                            • Announcing Early Access to "Zoho CRM for Everyone" — A new and exciting update to Zoho CRM

                                                                                                              Zoho CRM For Everyone is now officially available to all customers, and the Early Access Program has come to a close. We want to extend our sincere thanks to everyone who participated in the program. Your valuable feedback played a key role in shaping
                                                                                                            • Avalara Sales Tax integration - AVATAX

                                                                                                              Just wondering if anyone else is having troubles with this integration?  Seems as though Avalara changed their billing process, unbeknownst to Zoho, and now ALL transactions are counted by Avalara, not just transactions in a taxable jurisdiction.  This caused a huge price adjustment billed to us by Avalara within a month of us signing up.  And Avalara is not cheap to begin with! Avalara has been great in waiving that increase, but there seems to be no fix.  Zoho is aware of the problem, but slow
                                                                                                            • Invalid value passed for description

                                                                                                              Dear Sir, When I am entering the purchase bill , the following message showing "Invalid value passed for description" what should I do ? I am attaching screenshot. With Regards, Harish harish@cracku.in 7978841636
                                                                                                            • Zoho Creator - 2024 Release Projection 1

                                                                                                              Hello everyone! As we enter 2024, we'd like to extend our warmest wishes for success and prosperity. Your fantastic response to our Product Roadmap page last year has been incredibly motivating. Continuing on this path, we're excited to share a glimpse
                                                                                                            • Automation Assistance for Zoho Form Integration and Workflow

                                                                                                              Hi, We are currently using a Zoho Form to send out our Global Credit Application and would like to automate the process further. Specifically, we’d like the ABN number submitted through the form to automatically populate the GST/VAT Number field in Zoho
                                                                                                            • COQL does not return queryable value if the result set is empty

                                                                                                              See linked video for running code illustration of the problem: https://workdrive.zohoexternal.com/external/d49bb40033b43b288d56fdf843095b7c65b28391d3ec5d09c854f416d853003d Moderation update: We are appending the comment that was removed, to add context
                                                                                                            • Zoho CRMでの商談の管理のしかたについて初歩的な質問です。

                                                                                                              先月からZoho CRMを試験的に導入して運用しています。 商談の管理(運用?)の仕方について教えてください。 商談の数が増えてくると、ダッシュボードの「ステージ別進捗状況」にどんどん過去の商談が蓄積されてくると思うのですが、 現在動きのあるものを中心に確認したくなる気がします。 そのあたりについては、どのように運用が一般的なのでしょうか? アドバイスいただけるととてもありがたいです。 よろしくお願いします。
                                                                                                            • Composite Items & Purchase Orders

                                                                                                              The Composite Item is great way to bundle different products and services into a single line and sell it as a single line item in Estimates, Sales Orders and Invoices. However, on the other side - i,e,. Purchasing - this item creates quite a bit of a
                                                                                                            • using custom function is it possible to update the created by field in Zoho Crm custom module

                                                                                                              using custom function is it possible to update the created by field in Zoho Crm custom module
                                                                                                            • Slow Sloww Slowwww Responses

                                                                                                              Good day, Has anyone been experiencing slow responses from support? Since Thursday I migrated my Whats app to Sales Iq and I had to synch with Social to get the otp they were sending. Apparently What's app can't be automatically added so I reached out
                                                                                                            • You have exceeded the maximum number of attempts for this action. Please retry doing the same in 30 minutes.

                                                                                                              When one of Zoho Books user tries to select a vendor, recording a new bill, these message appears: You have exceeded the maximum number of attempts for this action. Please retry doing the same in 30 minutes. Other user, at the same time, but different
                                                                                                            • Enable Conversation Context Retention for SalesIQ Answer Bots

                                                                                                              Hello Zoho SalesIQ Team, We hope you are doing well. We have noticed that SalesIQ bots currently fail to maintain conversation context in Hebrew. For example, when we follow up on a previous answer or ask for clarification in Hebrew, the bot either provides
                                                                                                            • Automatic Hebrew Small Talk Setup Without Duplicate Term Errors & Manual Configuration

                                                                                                              Dear Zoho SalesIQ Team, Greetings, We would like to request an enhancement to the Small Talk feature in Zoho SalesIQ, specifically for Hebrew language support. Current Challenge: When setting up Small Talk for Hebrew, we encounter multiple issues: Simple
                                                                                                            • Should I Add Leads in Bigin?

                                                                                                              ok, first off I'm new here. I just started using Bigin. I'm debating if it's appropriate to enter leads. by leads I mean a list of contacts that I have not yet reached out to...it's a cold calling list.  if I enter them I can track them (I understand
                                                                                                            • Zoho Books - Perform a validation check before an invoice is marked as sent or sent

                                                                                                              Allow the validation rules to apply to button actions. For example: an invoice could not be sent or marked as sent if it has an empty value in a custom field. (The field could remain blank while it is being worked on.)
                                                                                                            • Flow error "given url is wrong"

                                                                                                              when I setup a flow to update a task status, I get an error when it runs that says "given url is wrong."
                                                                                                            • Upgrade Zoho Desk Agent-Side Answer Bot to GenAI

                                                                                                              Hello Zoho Desk Team, We hope you're doing well. Following the recent announcements and rollout of the GenAI-based Answer Bot in Zoho SalesIQ (Nova '25), we’d like to formally request a similar upgrade for the Answer Bot used by agents inside Zoho Desk.
                                                                                                            • Bigin Android app update: Email filters enhancement, change owner for related records.

                                                                                                              Hello, everyone! In the most recent Bigin Android app update, we have introduced additional email filters and an option to change the owner of related records. Email filters: We have now brought in support for 'All Emails' and 'Added from Widgets' filter
                                                                                                            • How can I get all conversations and comments of a Zoho Desk ticket using ZOHODESK

                                                                                                              Hi everyone, Currently, I am developing a Zoho Desk extension, and I am following the guide available at https://www.zoho.com/desk/extensions/guide/#ticket-object. While working with Zoho Desk, I have noticed that I can only retrieve the general information
                                                                                                            • AI & Zoho Recruit

                                                                                                              Hello, I guess we all are using AI in our personal and professional lives. Now, let's imagine. Recruitment is just a succession of stages and steps. For which step would you like to see AI implemented into Zoho Recruit ? I'll start : - Automatic translation
                                                                                                            • Workdrive and ChatGPT Team Synced Connectors

                                                                                                              Hi, we want to be able to integrate Zoho Workdrive with OpenAI’s ChatGPT Team plan. Google Drive and OneDrive both offer this, zoho please catch up asap. We dont want to have to put our company files in google drive, we want to allow chatgpt Team edition
                                                                                                            • widget url 404'ing

                                                                                                              I'm creating a widget for the first time. When I grab the url from the base url section of the widget builder and append /widget.html it 404's Just wrote a very basic test. I have a folder structure app.zip - widget.html --js/app.js /widget.html <!DOCTYPE
                                                                                                            • Unable to Edit Pick-List Items in Custom Project Field(s)

                                                                                                              I can edit most fields normally, but if I try to edit - in any way - a Pick List field, I just get this error: To be perfectly clear, I'm trying to edit an existing Pick List field (adding or removing items), not adding a new instance. If I rename it,
                                                                                                            • How to display results from zoho.crm.searchRecords in message window

                                                                                                              Hello, I've created a custom function which is linked to a custom button which pulls a date from our contacts module and searches a date field in our quotes module and returns all records matching the date. My issue is, how to I get this to display the
                                                                                                            • Domain Transfer

                                                                                                              Hello there! I wanted to know if I can transfer my domain from Zoho to other hosting providers or use a different hosting provider instead of zoho's services.
                                                                                                            • Select CRM Custom Module in Zoho Creator

                                                                                                              I have a custom module added in Zoho CRM that I would like to link in Zoho creator.  When I add the Zoho CRM field it does not show the new module.  Is this possible?  Do i need to change something in CRM to make it accesible in Creator?
                                                                                                            • New User - Opening Stock Aging Report

                                                                                                              I am setting up new client and am entering Opening Stock - created items and entered quantity/price details. Now the aging report is showing all the opening stock as new. How do I enter the Purchase Dates of these items so that I get accurate Inventory
                                                                                                            • Bulk Receive Multiple Purchase Orders

                                                                                                              Is there a feature or function that will allow you to bulk receive issued purchase orders? I have about 100 that need to be received from 5 years ago.
                                                                                                            • Manual Invoice

                                                                                                              How to create a Manual invoice, I need to enter Amount directly instead of (qty*Rate). our company is a service sector
                                                                                                            • Effective Inbox Organization: Folders vs Tags in Zoho Mail?

                                                                                                              I'm exploring the best ways to organize a busy inbox, especially when managing multiple clients or project using Zoho Mail. I’d love to know what works best for others: 1. Do you prefer **folders** (possibly with sub-folders) for each client or project?
                                                                                                            • Merging contacts and or accounts

                                                                                                              Hello, In a prior CRM we were able to merge contacts and or accounts.  We have turned on the function to stop multiple contacts with the same email, so we can prevent multiple contacts from happening, however, we now have multiple contacts that have the
                                                                                                            • Capture Reason for absence next to Campaign Member Status. Is there a reasonable workaround?

                                                                                                              I've reviewed the topics I could find to do with this but still couldn't find anything that satisfies our requirements: We would like to track a *reason* (picklist or text, doesn't matter which) why a Campaign Member (Lead or Contact associated with a
                                                                                                            • Zoho Learning Management System - Certificate Upload by Employees

                                                                                                              We are planning to enroll employees in courses which are hosted by coursera or similar sites. I want to share the links of those courses and also want employees to upload their completion certificate once they are done. Is this function possible in
                                                                                                            • Add RTL and Hebrew Support for Candidate Portal (and Other Zoho Recruit Portals)

                                                                                                              Dear Zoho Recruit Team, I hope you're doing well. We would like to request the ability to set the Candidate Portal to be Right-to-Left (RTL) and in Hebrew, similar to the existing functionality for the Career Site. Currently, when we set the Career Site
                                                                                                            • Button or Links order

                                                                                                              Is there a way to re-order the buttons or links that are created?
                                                                                                            • Next Page