Client Script for Custom Buttons

Client Script for Custom Buttons



Hello everyone!

Welcome back to another interesting and useful Kaizen post.

We know that Client Scripts can be triggered with Canvas buttons and we discussed this with a use case in Kaizen#180. Today, let us discuss how to trigger Client Script when a Custom Button is clicked. Using this, you can execute Client Script when a custom button is clicked.

In this post,


1. Event Details 
2. Supported Pages
3. Use Case - Export Subform Rows to Zoho Sheet in a Single Click!
4. Solution
5. Summary
6. Related Links



Client Script support for Custom Buttons opens up possibilities for automation, personalization, and enhanced user interactions in Zoho CRM when a custom button is clicked.
Here is a detailed walkthrough to help you understand it better.

1. Event Details 

The Button event triggers the Client Script when a custom button is clicked. Each time this event is invoked, the context argument is passed to the Client Script. The context contains information about the page from which the button was clicked.


Click here to know more about Client Script Events.

2. Supported Pages

A Custom Button can be placed in different positions based on the Page.


You can add a  custom button in the Util Menu, in Each Record or in the Mass Action Menu of the List Page.


Also, a Detail Page can have a custom button either In Record or in the Related List. Click here for more details about the different possible positions of a custom button.

The following table lists the supported pages and the corresponding context argument, which provides different details based on the page type.


To create a Client Script and make it trigger when a custom button is clicked, first create a Custom button and associate it with a Client Script as shown in the following image.


 Click here to view the steps to create a custom button and configure a Client Script. 

Note:

You can configure the Client Script only from the Buttons page to trigger it when a user clicks a custom button, and not the usual way of Creating Client Script via setup page. Once a script is created, it can be edited and updated from the Client Script setup page

3. Use Case - Export Subform Rows to Zoho Sheet in a Single Click!

Zylker manufactures medical instruments, and its sales representatives frequently need to share bulk order details with distributors and hospital partners using Zoho Sheets. These details such as product names, quantities, and prices are captured in a Subform on the Purchase Order Detail(Standard) Page.
To simplify this, the admin wants to add a custom button called "Export Products" on the Purchase Order Detail Page. When clicked, it should export the Purchase Items from the Subform and move the content to the specified sheet.

4. Solution

To export subform rows to Zoho Sheet with a single click, you can add a custom button to the Detail Page of the record. When clicked, a Client Script will be triggered to fetch the subform data from the Detail Page and pass it to a Function that uses zoho.sheet.createRecords() to insert data into Zoho Sheet.

Here’s how to implement this:

  • Add  “Export Products” custom button on the Detail Page.
  • Add the script to collect subform rows which invokes the Function.
  • Write a Function to create entry in Zoho Sheets  

A. Add “Export Products” custom button on the Detail Page.

  • Go to Setup → Modules and Fields under Customization.
  • Select a Module as Purchase Order.
  • Click on Buttons → Then click + New Button.
  • Enter Button Name and select Action Type as "Client Script"
  • Choose Button Position and Layout details as shown in the following image.
  • Click Create in Configured Client Script, enter the script, and click Add.
  • Select the profiles for which these buttons should be visible.
  • Click Save.



B. Add the Script to collect subform rows and invoke the Function

Use the following Client Script when you configure the custom button.

  1. var casesheetid = ZDK.Client.getInput([{ type: 'text', label: 'Enter the Sheet ID' }], 'Sheet details', 'OK', 'Cancel');
  2. if (casesheetid == null) {
  3.         ZDK.Client.showAlert("Enter the *Case Sheet ID - Import* to import data");
  4.  }
  5. var purchase_items = ZDK.Page.getField('Purchase_items).getValue();
  6. ZDK.Client.showLoader({type: 'page', template:'spinner', message: 'Export in progress, please wait'});
  7. var c=1;
  8. if (sheetid == null) {
  9.     ZDK.Client.hideLoader(); 
  10.     ZDK.Client.showAlert("Enter the *Case Sheet - Export* ID to export data");
  11. }
  12. purchase_items.forEach((r,i) => {
  13.             try {
  14.                resp = ZDK.Apps.CRM.Functions.execute("csvWrite", { "Product_Name": r.Product_Name.name, "List_Price": r.List_Price, "Discount": r.Discount, "Total": r.Total,"Sheetid":casesheetid }); }
  15.             catch (error) {
  16.                 c = 0;
  17.                  ZDK.Client.hideLoader(); 
  18.                 ZDK.Client.showAlert("Unexpected issue occured while adding data in row number "); }
  19.     });
  20.     ZDK.Client.hideLoader(); 
  21.     if (c) {
  22.         ZDK.Client.showMessage("Export completed. Please check the Sheet");
  23.     }
  24.     else
  25.     {
  26.        ZDK.Client.showMessage("Unexpected error "); }}

In this code, several ZDKs are used for various purposes. Click on the ZDK hyperlinks to learn more.


Note

The Client Script you intend to link with the button will be saved only after the custom button is saved.

C. Write a Function to create entry in Zoho Sheets 

  • Go to Setup > Developer Hub > Functions.
  • In the Functions page, click + Create New Function.
  • Choose the category as Button.
  • Click Create.
  • In the Create Function page, enter a name as csvWrite and description for your function.
  • Enter the following function code and click Save.
  1. string standalone.csvWrite(String product,String qty,String up,String amt, String Sheetid){
  2. queryData = Map();
  3. writeData = Map();
  4. header = Map();
  5. writeData.put("Product",product);
  6. writeData.put("Quantity",qty);
  7. writeData.put("Unit_Price",up);
  8. writeData.put("Amount",amt);
  9. SheetData = zoho.sheet.createRecords("Sheetid","Sheet1",writeData,queryData,"sheetconnection");
  10. return SheetData;
  11. }

Click here to know more about zoho.sheet.createRecords().

In the code above:
  • sheetconnection refers to the name of the Zoho Sheet connection, which must have the scopes: ZohoSheet.dataAPI.UPDATE and ZohoSheet.dataAPI.READ.
  • Click here to know how to create a Connection with the required scopes.
  • sheetid is the unique identifier of the Zoho Sheet, available in the sheet’s URL.
  • Sheet1 represents the name of the worksheet (i.e., the tab name shown at the bottom of the Zoho Sheet).
  • Now, when the custom button is clicked, the Client Script is triggered. It prompts for the Sheet ID, fetches the contents of the Purchase Order subform, and invokes a function that writes the content to the Sheet.
Here's how the Client Script works.



5. Summary

In this post we have seen,
  • What is a Button event?
  • How to configure Client Script for a custom button
  • How to write data into Zoho Sheets from Client Script
  • How to create a Function and call it from Client Script

6. Related Links


We are thrilled to be nearing the 200th post in our Kaizen series. As we approach this exciting milestone, we would love to hear from you. Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your input helps us improve and shape the series to serve you better.

Please take a moment to share your thoughts using ✨ this form 

We hope you found this post useful!

Happy Client Scripting! 😊

      Zoho Campaigns Resources


        • Desk Community Learning Series


        • Digest


        • Functions


        • Meetups


        • Kbase


        • Resources


        • Glossary


        • Desk Marketplace


        • MVP Corner


        • Word of the Day


        • Ask the Experts


          • Sticky Posts

          • 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.
          • 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.
          • 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

          Zoho CRM Plus Resources

            Zoho Books Resources


              Zoho Subscriptions Resources

                Zoho Projects Resources


                  Zoho Sprints Resources


                    Zoho Orchestly Resources


                      Zoho Creator Resources


                        Zoho WorkDrive Resources



                          Zoho CRM Resources

                          • CRM Community Learning Series

                            CRM Community Learning Series


                          • Tips

                            Tips

                          • Functions

                            Functions

                          • Meetups

                            Meetups

                          • Kbase

                            Kbase

                          • Resources

                            Resources

                          • Digest

                            Digest

                          • CRM Marketplace

                            CRM Marketplace

                          • MVP Corner

                            MVP Corner




                            Zoho Writer Writer

                            Get Started. Write Away!

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

                              Zoho CRM コンテンツ






                                ご検討中の方

                                  • Recent Topics

                                  • How to interact webhooks with Creator?

                                    How can I interact webhooks from external websites with Zoho Creator?  I'd like to get notifications from external websites (Stripe, Zoho Subscription, etc.) These notifications are coming as HTTP POST request from those servers, on maybe daily, monthly or based on any events.  How should I prepare my app in creator to receive these requests? Where and how to should I program in Deluge if I'd like to add some part of the JSON/XML data to my form?  Thank you BR, Balazs
                                  • Customising Sign Up Page in Zoho Help Centre Sandbox

                                    Hi, I would like to customise the Sign Up page in my Help Centre Sandbox Environment but when I try to access it I get this message: What setting or permission do I need to achieve this? Many thanks, Kunal
                                  • Related Lists filter

                                    I have Contacts showing in our Accounts module. I customized the Contacts module with an Employment Status field, with the following picklist options: "Primary Contact", "Secondary Contact", "Active Staff(not a main contact)", and "No longer employed".
                                  • Empowered Custom Views: Cross-Module Criteria Now Supported in Zoho CRM

                                    Hello everyone, We’re excited to introduce cross-module criteria support in custom views! Custom views provide personalized perspectives on your data and that you can save for future use. You can share these views with all users or specific individuals
                                  • Restricting Calendar View to Working Hours

                                    Hi: I'm trying to implement a calendar which displays all of my customer appointments.  Currently, the calendar shows all 24 hours of the day.  Is there a way to restrict the hours to simply the times my business is open? Thanks!
                                  • Color of Text Box Changes

                                    Sometimes I find the color of text boxes changed to a different color. This seems to happen when I reopen the same slide deck later. In the image that I am attaching, you see that the colors of the whole "virus," the "irology" part of "virology," and
                                  • Static Prefill URLs Functionality in the App

                                    Hi, It would be great to be able to use the same functionality within the App, so create the Static Prefill URL as today and be able to use online as today, and then have an area within the App showing these Entries that can be pressed and opens the form
                                  • How do I get at the data in "Partially Saved Entries"?

                                    Hi, Zoho Newbie here - I'm helping to support an existing Zoho installation, so this is all a bit new to me. I have to say, I'm liking what I've seen so far! We've just spotted that we have a number of respondents to our forms who don't end up submitting
                                  • Residual Formatting in Text Boxes After Undoing Pasting of Formatted Text

                                    Hi, guys! I have another problem to report. Actually, I have been aware of this for many months, possibly years, but I have been too lazy to report it to you. My apologies! Let's say you've pasted a formatted string into a text box. You change your mind
                                  • Ability to Initiate WhatsApp Template Messages in Zoho SalesIQ Without Preexisting Chat

                                    Hi Zoho SalesIQ Team, I hope you're doing well. I understand that with the WhatsApp integration in SalesIQ, clients can contact us via WhatsApp, and we can use WhatsApp templates to send messages outside of the 24-hour window by reopening an existing
                                  • Tabular View Report | Scale To Fit Screen

                                    Please add the option to scale Tabular View reports to fit the screen. I constantly have to adjust the column size of Tabular View reports to fit various screen sizes and it just looks messy. You can see in the screenshot below there is a blank gap after
                                  • Adding a work order for Assets vs. changing the contact person

                                    When adding a work order for an existing Assets (e.g. service), the assigned contact cannot be changed (deleting the contact deletes the selected Assets). This results in such an illogical operation that if you want to change the person to be contacted,
                                  • Zoho Projects - Q2 Updates | 2025

                                    Hello Users, With this year's second quarter behind us, Zoho Projects is marching towards expanding its usability with a user-centered, more collaborative, customizable, and automated attribute. But before we chart out plans for what’s next, it’s worth
                                  • Free Webinar : Unlock AI driven business insights with Zoho Inventory + Zoho Analytics

                                    Are you tired of switching between apps and exporting data to build customized reports? Say hello to smarter & streamlined insights! Join us for this exclusive webinar where we explore the power of the Zoho Inventory–Zoho Analytics integration. Learn
                                  • On click of the Blueprint transition (Qualified or Not Qualified), the 'Convert' option should be enabled in the Lead module.

                                    On click of the Blueprint transition (Qualified or Not Qualified), the 'Convert' option should be enabled in the Lead module. console.clear(); let convertButton = ZDK.Page.getButton('convert'); let leadStatus = ZDK.Page.getField('Lead_Stage').getValue();
                                  • Side-by-Side view on Windows 11

                                    Is there a way to open two notes in a side-by-side view? I'm running Notebook on a Desktop running Windows 11. If this feature doesn't exist, do you have plans for it?
                                  • Delivery Note Delivered item must be reduce in inventory stock

                                    When I create any Delivery note with product like mobile In our stock if it was 10 Unit I sold thru invoice, 4 unit And thru Delivery note, 2 Unit and I also change Delivery note status as delivered So in my stock it should display remaining 4 unit But write now it display 6 unit only. Please help me for that Because when I creating new invoice it display 6 unit in stock but actually in my physical stock its only 4. So I miss guide with stock display
                                  • Adding bills from docs *** Internal Error ***

                                    Same internal errors in Chrome & Edge !
                                  • How to start fresh after many years of using Zoho Books without deleting everything and creating a new organisation?

                                    Hi, I have used Books since 2016, but never reconciled with my bank account. I was thinking of trying to go back and fix that, but I don't just don't have the time it would take. Instead, I'd like back up my old records and start anew. What is the best
                                  • Response time when adding customers to the database is increasing over time.

                                    Response time when adding customers to the ZoHo books database is increasing over time. The response time to retrieve a newly added customer is now 1.5 to 2 minutes. The database has approximately 2,000 customers. I think you need to reorganise the
                                  • Excluded transactions in Banking

                                    Why are the payees not checked when 2 payments are for the same amount to avoid exclusion? If there are 2 ( or more ) payment amounts which are the same then they are automatically excluded, this should not happen unless the payee names are the same
                                  • Loan and purchase

                                    My husband is lending me mobey to buy a vehicle intersst free ... I need to know how to record the cash receipt and how I pay it back... the money is for a vehicle do I just post the invoice for that as I normally would usung the loan money to pay for
                                  • UK Registration for VAT with existing stock/inventory

                                    We have an existing inventory of stock and are investigating how to handle the conversion from a UK VAT unregistered company to a UK VAT registered company. Enabling VAT registered status looks extremely easy, but we cannot find any way within Books to
                                  • Zoho Voice & Zoho Recruit/CRM

                                    Hello, I'd love to use Zoho Voice with Recruit and CRM but it would need something very important to me, that has been a game changer to my daily routine, like Calendly has been for scheduling interview. It's call transcription with AI. I'm using Noota
                                  • Introducing Zia AI in Zoho Show

                                    AI is no longer a distant concept. It’s one of our everyday tools, from answering casual questions to generating critical business documents. And presentations are one area where AI can be especially helpful. At Zoho Show, we’ve been deliberate in how
                                  • Plug Sample #10 - Simplify Ticket Management (Zoho Desk) with Chatbots

                                    Hi everyone! We're here with another simple yet effective plug for your chatbot to integrate with Zoho Desk. When a customer reports an issue/request during chat, it's logged as a ticket on Desk. When they return for updates, you end up searching through
                                  • Trigger a field rule when Choice Availability reaches 0

                                    First of all, thanks for shipping the new Choice Availability counter. It solves the basic “stop over-booking” problem. What’s missing, though, is a way to react when an option is sold out. Right now we can only disable/hide the choice; we can’t fire
                                  • Unattended Access on Android without Play Store

                                    I'm testing Zoho Assist for remote config and maintenance of our IoT devices. The devices are running Android 8.1 and do NOT have Google Play Store installed, nor can it be installed. I've been able to install Zoho Assist on the devices and load the enrollment
                                  • Zoho People > Performance Management > Appraisal cycle

                                    Hello All I am using this 2 users to test out how it work on Performance Management User 1 - Reportee User 2 - Reporting Manager : Li Ting Haley User 1 : Self Appraisal Error How do i fix this error?
                                  • What's New - June 2025 | Zoho Backstage

                                    Plans change. People cancel. Tickets get handed off. It happens, and we understand. As an organizer, you need tools that offer flexibility for attendees while protecting your event’s integrity. That’s why we’ve built features to help you manage these
                                  • Include Article Sync Details in SalesIQ–Desk Integration Notification Email

                                    Dear Zoho SalesIQ Team, Greetings, We are using the integration between Zoho SalesIQ and Zoho Desk to sync articles from the Zoho Desk Knowledge Base into SalesIQ. As part of this integration, we receive the following email notification: "Your scheduled
                                  • Sync Zoho Desk Help Center Category Icons to SalesIQ Articles

                                    Dear Zoho SalesIQ Team, Greetings, We are using the integration between Zoho SalesIQ and Zoho Desk to sync articles from our Zoho Desk Knowledge Base into SalesIQ. While this integration works well for syncing article content, we’ve noticed a visual inconsistency:
                                  • Naming a Visitor in SalesIQ Messes up First and Last Name

                                    When I go to Visitor History to manually associate a visitor with a known contact, I press the pencil symbol next to the system-generated ID number. I enter first and last name, then email. Looks good so far. However, when it syncs with CRM, first name
                                  • Partial Sync

                                    Hi, got an issue with syncing cards across windows app, web app and iphone app. If I create a card and add some text content then everything syncs across all platforms ok. If I create a card and add an attachment, be it pdf, jpg or movie then the card
                                  • Pick List Issues

                                    I have created a pick list that looks at a table in a sheet, it selects the column I want fine. Various issues have come along. The option to sort the pick list is simplistic, only allows an ascending alphabetical sort. Bad luck if you want it descending.
                                  • Related activity records for custom modules

                                    For default modules in CRM, whenever I create a task for a contact, the task also appears in the record for the parent account. How do I replicate this with custom modules? My specific situation is that I have a custom module as a child module to Accounts.
                                  • 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
                                  • Why Do My Portal Users Can't See Any Data in Reports

                                    In My zoho crm i have created a button automation which basically is it converts a quote into invoice and sales order , so initially when a person who is my app user submits a quotation form it goes into quote module and record is created and in each
                                  • Introducing Zoho Commerce 2.0 — It's more than just selling!

                                    Hello! We are proud to launch Zoho Commerce 2.0, a reimagination of how online businesses look, feel, and function. This launch is both timely and symbolic, as we reaffirm our commitment to empowering small and medium enterprises with powerful, yet simple-to-use
                                  • Product and Service

                                    Hi guys, there is a difference between layout of product and service if Long Description field have some kind of text. Please see screenshot 1 for Service here: https://prnt.sc/7xWwPKd29nWP for Product here: https://prnt.sc/LGmtVd_U6H7q As you can see
                                  • Next Page