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

                                                                                                            • How to see history on Bulk send of Customer Statements

                                                                                                              Hi, We bulk send statements to customers every month via Books - every month we have customers emailing requesting a statement. Currently I have no visibility on if a customer was sent the statement or not and if our process is being followed or overlooked
                                                                                                            • Guided Conversations - Ticket Creation

                                                                                                              Hi there, Using Guided Conversations to Take Customer Data and apply it into a Support Ticket for internal use, Is there a way to take multiple Textual Variables Inputs (A series of questions), and have the answers all appear in the Description of the
                                                                                                            • How to add buttons elements in the Header

                                                                                                              I am trying to add CTA (Call to Action) buttons in the right side of the main navigation menu. This is a common practice for sites but I can't seem to figure this out for Zoho Sites. Is there a custom workflow that could be shared with me? 
                                                                                                            • Automatic back up - Zoho Recruit, books, people,crm, analytics

                                                                                                              Hello, Has anyone found a good way of automatically backing up Zoho (CRM, expense, recruit, people, books, analytics).? I have found with tool that does, but it doesn't include recruit or analytics It's a bit annoying and time consuming having to go to
                                                                                                            • delete departments on zoho desk

                                                                                                              I created test departments on zoho desk. how can i delete them now?
                                                                                                            • Validation, checking if a file has been attached to the ticket

                                                                                                              A very useful option would be to allow checking, under specific conditions, whether the user has attached a file to the application, e.g., a bug report. Some applications require files to be attached, and the system could enforce this after the system
                                                                                                            • 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
                                                                                                            • Zoho Flow not handling Boolean properly

                                                                                                              Hi, I have a checkbox in one system that I'm trying to sync with a checkbox in Zoho CRM. The value from the source system comes in as blank (unticked) or 1 (ticked). I've written the following custom function to convert the output to either boolean false
                                                                                                            • Quotes Module - import data

                                                                                                              Hello Zoho, is it possible to import Quotes records? I was trying and i have no results. Raport shows no data imported. Could you help me please how to do it?
                                                                                                            • Balance Sheet - Zoho Analytics

                                                                                                              Hi Team, I’m looking to implement a feature that captures the conversion rate based on the filters applied. By default, it should fetch the most recent conversion rate, and when a filter (such as a timeline filter) is applied, it should return the conversion
                                                                                                            • files sent will not open for recipient

                                                                                                              work files (done in writer) which previously opened will not open for the recipient
                                                                                                            • How to Print the Data Model Zoho CRM

                                                                                                              I have created the data model in Zoho CRM and I want the ability to Print this. How do we do this please? I want the diagram exported to a PDF. There doesnt appear to be an option to do this. Thanks Andrew
                                                                                                            • Cisco Webex Calling Intergration

                                                                                                              Hi Guys, Our organisation is looking at a move from Salesforce to Zoho. We have found there is no support for Cisco Webex Calling however? Is there a way to enable this or are there any apps which can provide this? Thanks!
                                                                                                            • Migration of Mails from Pipedrive

                                                                                                              Hi, so far the migration from Pipedrive to ZOHO works pretty good. For full completeness of the migration we miss all the mails linked to Deals, Contacts, Customers, ... What possibilities do we have to have Pipedrive fully migrated to ZOHO? Best Regards,
                                                                                                            • Published sheets don't work anymore

                                                                                                              Hi, Published sheets don't work anymore. The display of values is very very slow and calculations are not displayed at all. Thanks!
                                                                                                            • WorkDrive TrueSync for macOS 26 (Tahoe) Beta

                                                                                                              Hello everyone, With Apple unveiling the macOS 26 (Tahoe) Beta, we know many of you are eager to explore the latest features and enhancements. We’re excited to support your enthusiasm! As part of our commitment to delivering seamless cross-platform experiences,
                                                                                                            • Limited layout rules in a module

                                                                                                              There is a limit of 10 layout rules per module. Is there a way to get that functionality through different customization or workflow + custom function (easily accessible), etc. Having just 10 is limiting especially if module contains a lot of data. Are
                                                                                                            • #1 Zoho Billing vs. Zoho Books: Which one should I choose?

                                                                                                              Managing your business finances isn't just about sending invoices. It's about keeping everything organized, accurate, and moving towards your organization's goals. At Zoho, we understand the complexity, which is why we offer two powerful yet distinct
                                                                                                            • Is Zoho tables still being developed?

                                                                                                              Has this product been abandoned? I haven't seen any useful new features or stability improvements over the past six months or more. I think Tables is a great concept, filling a niche between spreadsheets and full database tools, but the current implementation
                                                                                                            • How to connect oracle ADW with Analytics

                                                                                                              I want to add Oracle ADW as a data source in Zoho Analytics, but I couldn't find any relevant documentation. Can anyone suggest how to do it, or let me know if it's even possible? Thanks!!
                                                                                                            • RAG (Retrieval Augmented Generation) Type Q+A Environment with Zoho Learn

                                                                                                              Hi All, Given the ability of Zoho Learn to function as a knowledge base / document repository type solution and given the rapid advancements that Zoho is making with Zia LLM, agentic capabilities etc. (not to mention the rapid progress in the broader
                                                                                                            • add attachments to automated emails?

                                                                                                              Hi, I'm looking for a way to have documents saved under an account, be grabbed and sent to an email address once a specific status has been updated.  For example we have a tab we've labeled as sales orders, when the status is changed to shipped, it emails the customer the tracking number and estimated delivery date.  I'd like it to also grab pdf docs (COA, BOL, etc) from that order and send in that email.   Currently we have to go into zoho change the status to shipped, then email all the docs to
                                                                                                            • [Action Required] Zendesk - Zoho Analytics integration requires re-authentication

                                                                                                              Dear Zendesk integration users, Zendesk is transitioning to a new OAuth model that uses refresh tokens for improved security and stability (read more). As a result, all Zendesk users in Zoho Analytics must re-authenticate their Zendesk connections on
                                                                                                            • Rerun Migration?

                                                                                                              I migrated a mailbox a few days ago, but didn't do the cutover on the MX records until today.  How can I rerun the migration to sync the mailboxes?  The old account has had a fair amount of activity since the first migration. I am used to other systems
                                                                                                            • طلب حذف الدومين والمؤسسة من حساب zoho

                                                                                                              السلام عليكم، أود طلب حذف الدومين التالي من حسابي في Zoho، حيث لا يظهر لي خيار الحذف في لوحة التحكم: اسم الدومين: hudajstore.com البريد المرتبط: [contact@hudajstore.com] علمًا بأنني المسؤول عن المؤسسة، ولا أستخدم الدومين حاليًا، وأرغب في إلغاء ربطه وحذف
                                                                                                            • Microsoft Outlook Add-in Update: Enhancing Efficiency for Recruiters

                                                                                                              We've released an update to the Zoho Recruit Microsoft Outlook Add-in, which brings a host of features designed to streamline your recruiting process and boost productivity. Let's delve into the details: Associate Emails with records in Zoho Recruit You
                                                                                                            • New integration: Zoho Books + Zoho Forms

                                                                                                              Hello Zoho Forms community! We are thrilled to announce the addition of another integration that brings speed and efficiency to your financial workflows. Zoho Forms can now be integrated with Zoho Books! Here’s a quick rundown on Zoho Books! For anyone
                                                                                                            • Witness Sign - Automation with Zoho Creator

                                                                                                              Hi there, I used to be able do automatically send a Zoho Sign document from Zoho Creator where each signer had one witness. The action code was as follows for each signer and witness:       // CLIENT eachActionMap1 = Map(); eachActionMap1.put("signing_order","1");
                                                                                                            • Announcing: custom color palette + free workshop

                                                                                                              Hello everyone, We're excited to share new feature in Zoho Bookings—a color palette within booking page themes. You'll find this option under Manage Bookings > Workspaces > Booking Page Themes. You can customize the color of every element in your booking page and even alter the transparency of your background image. Please note that this is a paid feature included in the Basic and Premium plans. At the moment, it's available only under the Modern Web theme. This means you can create billions (7,
                                                                                                            • Removing To or CC Addresses from Desk Ticket

                                                                                                              I was hoping i could find a way to remove unnecessary email addresses from tickets submitted via email. For example, a customer may email the support address AND others who are in the helpdesk notification group, in either the TO or CC address. This results
                                                                                                            • Ability to Export Field Dependency Structure in Zoho Desk

                                                                                                              Hi Zoho Team, We’d like to request a feature enhancement in Zoho Desk that would greatly improve configuration management for organizations like ours: Requested Feature: The ability to export the full structure of Field Dependencies, especially for multi-level
                                                                                                            • [URGENT] Allow reorder (drag&drop) of subform record

                                                                                                              Very simple user case: a wedding planning app where you want to send your client a form to fill with information about their wedding. Form includes some field for general purpose information and a subform for event pacing/schedule. Clients are invited to create a new row (When? - What? - Where? - Who?) for each thing happening during their wedding chronologically. Ex: When                  What 10h                      Something TBD                    Speech After speech      Yet another thing happening
                                                                                                            • Departments in Zoho

                                                                                                              I'm trying to set up a department. It looks like Departments have been removed from Zoho One. Is there another option? We have our main account setup, but want to set up a separate small department that can't see our tabs.
                                                                                                            • Add Timer for Agent Status Duration in Zoho Desk Dashboard

                                                                                                              Hello Zoho Desk Team, We hope you're doing well. We would like to submit a feature request to further enhance the agent status tracking functionality within the Zoho Desk Dashboard. 🎯 Current Functionality As it stands, Zoho Desk allows us to view the
                                                                                                            • [Beta Feature] Parent-Child Ticketing

                                                                                                              Hello there, a beta parent-child ticketing feature has recently been made available for some, read more here: https://help.zoho.com/portal/en/kb/desk/ticket-management/articles/understanding-parent-child-ticketing-system#Business_scenarios I would like
                                                                                                            • Enable Sorting by Ticket Count in Category Reports

                                                                                                              Hi Zoho Desk Product Team, I hope you're doing well. We would like to submit a feature request to improve the reporting capabilities in Zoho Desk. 🎯 Feature Request: Sorting by Ticket Count in Category Reports Currently, category-based reports in Zoho
                                                                                                            • Reactivating a CRM user...

                                                                                                              I'm a 1-man business primarily using CRM under my Zoho1 subscription (I have NO other employees or users). I wish to re-activate a prior user (my son, once more working with me) but when changing his status from inactive to active I receive this message:
                                                                                                            • Zohoサポートにスコープ開放を依頼する

                                                                                                              お世話になっております。 現在、弊社にてZoho DeskのナレッジベースをAPI経由で取得し、AIツール(NotebookLM等)に連携する仕組みの構築を検討しています。 つきましては、ZohoDesk.articles.READ スコープを使用したOAuth認証の許可をいただけますでしょうか。 API Console から Server-based アプリを作成済みですが、認可URLにアクセスすると「スコープが登録されていません」と表示されます。 お手数をおかけしますが、スコープの開放をご
                                                                                                            • Where can I configure the notifications for everything KB-related?

                                                                                                              Hi all, I'm receiving notifications for some actions happening in our Knowledge Base (e.g. someone leaving a feedback) and I would like to customise the template or have the choice to enable/disable such notifications like it is possible for ticket notification
                                                                                                            • Increase Round Robin Scheduler Frequency in Zoho Desk

                                                                                                              Dear Zoho Desk Team, We hope this message finds you well. We would like to request an enhancement to the Round Robin Scheduler in Zoho Desk to better address ticket assignment efficiency. Current Behavior At present, the Round Robin Scheduler operates
                                                                                                            • Next Page