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! 😊
    • 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
    • Recent Topics

    • メール一括配信の未送信のメールについて知りたい

      メール一括配信の後の、未送信のメールの数は添付のようにシステムから連絡がくるのですが それらの対象者を知りたい。レポートなど一覧で知りたい。 また配信対象者なのに(担当者、リード)の メールの履歴に配信したメールの件名でさえ表示されないのはどう理解したらよいのか知りたいです。 また、これらの人をレポートで一覧で出す方法を教えてください。把握したいためです。
    • Shipment

      I have 70 shipments Out of which 40 delivery date are updated( since it is live tracked) 30 numbers i need to update manually. How to do it in bulk?
    • arabic not printing

      Qatar has a legal requirement to have invoices in English and Arabic. When writing invoice fields in Arabic, they don't print. Why?
    • How to show Order Number/SO Ref on Invoice emails

      When creating a sales order or invoice we have an option to input an order number or ref# (see attached images). For the Sales Order email template we can add a placeholder for the SO_REF. However, for the Invoice email template there's no option to reference
    • Is it possible to Bulk Update 'Product Name' in Zoho Desk?

      Is it possible to Bulk Update 'Product Name' in Zoho Desk? I cannot see that option now. Kindly help how we can do it.
    • How to turn off ability to share Knowledge-base article with social networks

      Is there a way to deactivate the link at the bottom of a Knowledge-base article so that it can not be shared via Facebook or Twitter?
    • Useful enhancements to Mail Merge in Zoho CRM

      Dear Customers, We hope you're well! We're here with a set of highly anticipated enhancements to the Mail Merge feature in Zoho CRM. Let's go! Mail Merge in Zoho CRM integrates with Zoho Writer to simplify the process of customizing and sharing documents
    • ZOHO Desk blocking emails from creating tickets

      Hi We have been noticing some issues since last week ZOHO Desk is not creating a ticket which is still in our affiliate mail box.
    • ZOHO Desk blocking emails from creating tickets

      Hi We have been noticing some issues since last week ZOHO Desk is not creating a ticket which is still in our affiliate mail box.
    • Workerly/Zoho One Pricing

      Hi What is the pricing model that is suppose to be as a Zoho One user? If i use the services of a freelancers or temp workers (Sometimes for a few hours a week/month), I need to purchase a zoho one license for each of them as well as workerly licenc
    • An Exclusive Session for Zoho Desk Users: AI in Zoho Desk

      A Zoho Community Learning Initiative Hello everyone! This is an announcement for Zoho Desk users and anyone exploring Zoho Desk. With every nook and corner buzzing, "AI's here, AI's there," it's the right time for us to take a closer look at how the AI
    • Multi Level Hierarchical Query

      Hi guys I have a situation where i am trying to extract the descendants of a particular entry.  So long story short, i have the Account table with Agency (A) id = 1, and that has child Agency (B) id = 2. This child agency (B) has a child agency (C) id = 3. This child agency (C) has a child agency (D) id = 4.  So in essence we have have a pyramid setup where each level has other child agencies underneath. The number of levels differ per the preceding Agency. My question now is, in Analytics how do
    • Specify in-line image size in question

      I have an image inserted into a file upload type question. I can click and drag the corner of the image to make it larger or smaller, but I would like to manually input the dimensions I need. No matter what size I make the image in photoshop before uploading
    • Can you limit who creates tags?

      Hi there, I'd like to find out if it's possible to limit which Agents create tags on Zoho desk. Thank you. 
    • Auto CC - Moving Departments

      We have Auto CC e-mail replies to your support mailbox enabled. We have two departments: Helpdesk (helpdesk@domain.com) Delivery (delivery@domain.com) If we create a Helpdesk ticket, and reply, replies are CC'd to helpdesk@domain.com (OK) We then move
    • Rich Text For Notes in Zoho CRM

      Hello everyone, As you know, notes are essential for recording information and ensuring smooth communication across your records. With our latest update, you can now use Rich Text formatting to organize and structure your notes more efficiently. By using
    • Automatically Hide Unauthorized Sections from Agent Interface in Zoho Desk

      Hello Zoho Desk Team, We hope you're doing well. We’d like to submit a feature request regarding the user experience for agents in Zoho Desk who do not have permission to access certain sections of the system. 🎯 Current Behavior At present, when an agent
    • [Important announcement] Zoho Writer will mandate DKIM configuration for automation users

      Hi all, Effective Dec. 31, 2024, configuring DKIM for From addresses will be mandatory to send emails via Zoho Writer. DKIM configuration allows recipient email servers to identify your emails as valid and not spam. Emails sent from domains without DKIM
    • Is there a way to prevent a user from removing a payment method on a live, recurring subscription?

      As it stands, if you allow users to remove payment methods, they can do so on live subscriptions. This leaves the sub without a payment method. The user should be able to REPLACE the card with a new one, but not remove all payment methods. We have had
    • Multi file upload

      Hi, I just wonder if one could upload multiple files in one shot, say between one and three files, without adding multiple File Upload fields? Thanks, Alalbany
    • Try CRM for everyone button in the way of workflow

      Please consider using the bottom bar for offers. Using the top bar for offers like "Try CRM for everyone" really gets in the way of my day to day workflow.
    • 🚀 WorkDrive 5.0: Evolving from a file sharing app to an intelligent content management platform: Phase 2

      Hello everyone, WorkDrive's primary focus has always been to provide an intelligent and secure content management platform, simplify collaboration, and be the central repository of files for all Zoho apps. In our previous announcement, we unveiled the
    • Function #25: Automatically generate purchase orders from a sales order

      We kicked off the "Function Fridays" series with the goal of helping you automate your everyday accounting tasks. As we delve into today's post, I'm delighted to announce that we're here to present the 25th custom function in this series. While it is
    • Sudden Layout Issue After Last CSS Update for ZML (Temporary Fix Inside)

      Hi, Our clients have noticed today that every section laid out with ZML suddenly shows an unwanted top padding/blank space that interrupts the user screens. It appears that Zoho has changed the default CSS for the .zcp-col.zcp-panel-rowtype-auto element.
    • Search Bar Improvement for Zoho Commerce

      Hey everyone, I've been using Zoho Commerce for a bit now, and I think the search bar could really use an upgrade. Right now, it doesn't show products in a dropdown as you type, which would make finding items a lot faster. On Shopify, for example, you
    • 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
    • is it possible to add more than one Whatsapp Phone Number to be integrated to Zoho CRM?

      so I have successfully added one Whatsapp number like this from this User Interface it seems I can't add a new Whatsapp Number. I need to add a new Whatsapp Number so I can control the lead assignment if a chat sent to Whatsapp Phone Number 1 then assign
    • Why Server error in creatiing Landing Pages

      Hi Zoho Team, pls see my screenshot and tell me, what's wrong. Thx
    • Formula Fields inside of Blueprint Transitions

      We would like to have formula fields inside of blueprint transitions. We type in currency fields and would like to see the result inside of a formula field. Our use case: Send out a price for XY 1. Filling out cost fields 2. See gross profit
    • How to create a directory report from one-to-many relationship

      Hi all, Newbie here. I'm converting an Access DB to Creator. I've learned Forms are tables and Reports are used to edit table rows, not Forms. I've got the data loaded and can maintain it with the Reports already done. I've done filtering and sorting,
    • Tip 31: How to make a field in a Zoho Creator form mandatory based on criteria

      Hi folks,   I'm sure most of you are familiar with the Mandatory property available in our form builder. It enables you to ensure that your users enter an input in a required field. If they don't enter an input in that field, they'll be unable to submit
    • Assistance Required: Report Export to Excel and WorkDrive Upload via Deluge

      I'm working on automating a scheduled workflow in Zoho Creator that needs to run weekly. The goal is to: Export a report from Zoho Creator in Excel (.xls or .xlsx) format, and Upload the exported file to a specific folder in Zoho WorkDrive using a Deluge
    • Avoiding Inventory Duplication When Creating Bills for Previously Added Stock

      I had created several items in Zoho Books and manually added their initial stock at the time of item creation. However, I did not record the purchase cost against those items during that process. Now, I would like to create Purchase Orders and convert
    • Bulk update account type when adding a bill

      Hi I've only been using Zoho Books for a short while but I'm impressed so far, keep up the great work. One minor issue I'm coming up against is when creating a new bill from a scanned document (supplier invoice). In some cases, the supplier invoice could
    • 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
    • How do I modify the the incoming/current call popup? I can modify other call pages but not that one.

      I want to modify the incoming and active call popup on the crm to include customer relevant information, such as purchase history or length of relationship. Under modules and fields, I don't seem to see active call as a choice to modify, only the main
    • Interactions Tab in Zoho CRM: A 360° Omnichannel View of Every Customer Touchpoint

      Hello Everyone, Hope you are well! We are here today with yet another announcement in our series for the revamped Zoho CRM. Today, we introduce Interactions Tab a new way to view all customer interactions from one place inside your CRM account. Customers
    • Canvas: Add Sections to Detail View

      Currently it is only possible to add fields to a canvas detail view. This makes Canvas hard to maintain, because everytime we add a field to our system, someone needs to go into the canvas view and add it there as well. This leads to additional work and
    • Automation#32:Auto Add New Portal Users to the Help Center User Groups

      Hello Everyone, Introducing a custom function that automates the process of adding new portal users to Help Center user groups, making user management effortless! By default, Zoho Desk allows you to assign new portal users to groups manually. But with
    • View Linked Subscription on Invoice list

      When looking at the list of invoices in billing is it possible to see the subscription that an invoice is for. This would allow you to see if it's a subscription a customer is behind on, or they simply haven't paid a one time invoice.
    • Next Page