Guide: Learn How to Deploy Client Script across Zoho CRM and Best Practices to Optimizing Code

Guide: Learn How to Deploy Client Script across Zoho CRM and Best Practices to Optimizing Code

In this article, we will explore the "Client Script" features in Zoho CRM, along with detailed guidance on how users can deploy these scripts across different places within the Zoho CRM organization.

Client Script

Client Script is a piece of JavaScript code that runs directly in your web browser instead of the server, thus returning an immediate response. In Zoho CRM, Client Scripts are executed based on predefined event triggers in the client web browser. i.e., Based on the client-specific actions (such as - onLoad of Page, onChange on Field, onClick of Button), we can trigger the Client Script and perform the specified custom actions.

For example: When a client fills an email address in 'Email' field of a Lead/Contact, we can perform an Email Discovery and automatically populate relevant information (such as - First Name, Last Name, Phone, etc.) within the same page (i.e., Create Page, Edit Page, etc.) in the respective fields.
  1. Deploy Client Script in various places

Such as
-> On_Load/On_Save/On_Edit of Page, On_Type/On_Change of Field, Subform Events, Blueprint Events, List View Events, etc.
-> Commands/Shortcut Keys (Trigger script from anywhere & anytime in CRM).
-> Custom Button (Recent Enhancement)
-> Notes Related List within any record (Recent Enhancement)
-> On Client Portals (Recent Enhancement)

NotesRefer to the following Help Reference to know more about Client Script Events Details.
  1. To Create Client Script:

You could add Client Script through two ways:

1. Through Setup Page:

Navigate to Setup (⚙️) in Zoho CRM >> Developer Hub >> Client Script >> New Script.


-> Provide a Name & Description appropriate to script

-> Category Details -
  1.       Select Category based on requirement. Module - triggers via Events || Commands - triggers via Command Pallet/Shortcut Keys.
  2.       Choose Module where you want to add script. i.e., Lead, Contact, etc.
  3.       Choose Page to deploy script in specific page. i.e., Create, Edit, Clone, Detail, List, etc.
  4.       Choose Layout. i.e., Standard or Custom layouts.
-> Event Details - 
      Select Event Type - Field Event or Page Event or Subform Event
  1.       Field Event -> Select the Field & Event (i.e., onChange on First Name field).
  2.       Page Event -> Select the Page & Event (i.e., onLoad on Create Page).
  3.       Subform Event -> Select the Subform & Event (i.e., onCellChange).

2. Through Detail/List/Create/Edit/Clone Pages of a Record in Module

-> Choose a desired module in Zoho CRM, and open either the List, Create, Detail, Edit or Clone page of any record in that module. For example, consider the Create Lead page.
-> For Pages (such as Create/Edit/Clone) - In the right-most corner of the page, click Client Script. Then, Add script.
-> The Category details will be pre-populated by the system. Fill in the other details of the client script, such as Name, Description, Event Details of the client script. Further, click next and add your script to the code editor in Client Script IDE. Then click Save and Close.

Add Client Script via Detail Page:


Add Client Script via Different Pages such as List/Create/Edit/Clone:


TIPS: How to Optimize the Code in Client Script

It is essential to write code in an optimized way to ensure smooth execution and avoid potential errors when working with Client Scripts in Zoho CRM. This also helps to enhance performance, maintainability, reduce unwanted API calls and a well-structured code with optimal logic. 
  1.  Avoid Repetitive Code

-> Client Script supports a standard sub-feature called "Static Resources". It provides an easier way to import existing code files in the form of static resources and use them in your script. You could upload a Javascript file as a static resource, include the uploaded file in your script using the Add button on the right panel of the Code Editor, and call the function in the static resource file from your script whenever it is required. Refer to Static Resources in Client Script for more information.
  1. Use default ZDK Client methods and Web CRM API

-> Client Script provides ZDK (i.e., Zoho Developement Kit) libraries with various default built-in methods, which help users to make the business process in more efficient way within Zoho CRM. Using these readily available methods, we can perform default actions such as showing pop-up/alert, fetch/update record data instantly, fetch logged-in user's/Org's information, etc. Learn more about Client API with samples.

-> Similarly, we support various Web CRM methods that serve as wrappers of the Zoho CRM REST APIs, and users can use them directly within Client Script and make the necessary actions within Zoho CRM. Refer to CRM API for more information and direct samples.
  1. Minimize Web API calls within Zoho CRM

-> Every Web API will consume an API credit, same as mentioned for Zoho CRM APIs used within Custom Function/Developer Tool/Third-party system. For example: fetchById (Web API) consumes the same credits as per 'Get Record' CRM API. Whereas, the Client API will not consume any credits, as it's a UI action on the client end. Excess API calls (or repeated API calls within Loop) may cause API usage to exceed the allowed limits.
  1. Avoid Unnecessary Loops:

-> If you are using a for() Loop in a script, then try to filter the records before it enters into the loop. You could also add an IF condition inside the 'for() Loop' to filter records within the loop.

-> Use Bulk CRM APIs, which make bulk actions (such as bulk read or bulk write) instead of looping through individual API calls. Users can call the Zoho CRM API within their Client Script using the default Connection method. 
  1. Usage of Variables & Logging in Production

-> While writing the script, users can add log()/console.log() to each variable to check the output for seamless functionality. Users can view the output in the "Messages" tab within Client Script IDE for each logs() print. To view console logs, you could follow - "Right Click on browser page >> Inspect >> Console".

-> After the complete code testing, we would suggest to remove or comment out logs and unused variables to make the script cleaner and easier to debug in the future.

-> Ensure to use the meaningful variable names you define, which clearly reflect the data they store or the purpose they serve. This improves the readability of your script and makes debugging & collaboration significantly easier.

For example:

      // ❌ Not recommended
  1. x = input.get("Account_Name");
  2. var ar = ZDK.Apps.CRM.Leads.fetchById( record_id );

      // ✅ Recommended
  1. accountName = input.get("Account_Name");
  2. lead = ZDK.Apps.CRM.Leads.fetchById( record_id );
  1. Use Try-Catch Blocks
-> Use try-catch blocks to handle exceptions smartly without wrapping every line in a try. Log required error messages that help trace the exact problem with the line of code. Refer to the below example syntax to use Try-Catch in Client Script.
  1. //Below code has syntax error at line 4 while updating the field. Hence, an exception thrown via Catch.
  2. try {
  3.     value = "test"
  4.     ZOHO.CRM.FIELDS.setValue("City", value); //incorrect syntax
  5. }
  6. catch(e) {
  7.     log("e     ", e)
  8.     log("e.message.   ", e.message);
  9. }
  1. Use Null Check to Prevent Errors

-> When you use the get() method in Client Script, you could include a null check to avoid any errors that say "undefined/null".
In Client Script, user can use below to check null results:

Using || operator  - This helps to assign 0 if the value is null, undefined, "", or 0.
  1. phone = ZDK.Page.getField("Phone").getValue();
  2. getFieldVal = phone123 || 0;  
  3. log(getFieldVal);                                //phone123 is not defined - result is "0"
Using ?? operator (recommended) - This helps to assign 0 if the value is null or undefined, but not if the field is an empty string or 0.
  1. emptyStr = "";
  2. getName = emptyStr ?? 0;
  3. log(getName);                                      //no string - result is empty result instead of 0 
Using if() condition - Users can also use if condition to check field value and assign 0.
  1. let phone = ZDK.Page.getField("Phone").getValue();
  2. if (phone === null || phone === undefined || phone === "") {
  3.     phone = 0;
  4. }
  5. log(phone);
Info
Refer to the Sample Codes to learn more about Client Script.



If you need any further clarifications, please don’t hesitate to contact partner-support@zohocorp.com.
Notes
Additionally, we kindly ask all Europe and UK Partners to reach out to partner-support@eu.zohocorp.com.

      Create. Review. Publish.

      Write, edit, collaborate on, and publish documents to different content management platforms.

      Get Started Now


        Access your files securely from anywhere

          Zoho CRM Training Programs

          Learn how to use the best tools for sales force automation and better customer engagement from Zoho's implementation specialists.

          Zoho CRM Training
            Redefine the way you work
            with Zoho Workplace

              Zoho DataPrep Personalized Demo

              If you'd like a personalized walk-through of our data preparation tool, please request a demo and we'll be happy to show you how to get the best out of Zoho DataPrep.

              Zoho CRM Training

                Create, share, and deliver

                beautiful slides from anywhere.

                Get Started Now


                  Zoho Sign now offers specialized one-on-one training for both administrators and developers.

                  BOOK A SESSION







                              Quick LinksWorkflow AutomationData Collection
                              Web FormsRetailOnline Data Collection Tool
                              Embeddable FormsBankingBegin Data Collection
                              Interactive FormsWorkplaceData Collection App
                              CRM FormsCustomer ServiceForms for Solopreneurs
                              Digital FormsMarketingForms for Small Business
                              HTML FormsEducationForms for Enterprise
                              Contact FormsE-commerceForms for any business
                              Lead Generation FormsHealthcareForms for Startups
                              Wordpress FormsCustomer onboardingForms for Small Business
                              No Code FormsConstructionRSVP tool for holidays
                              Free FormsTravelFeatures for Order Forms
                              Prefill FormsNon-Profit
                              Forms for Government
                              Intake FormsLegal
                              Mobile App
                              Form DesignerHR
                              Mobile Forms
                              Card FormsFoodOffline Forms
                              Assign FormsPhotographyMobile Forms Features
                              Translate FormsReal EstateKiosk in Mobile Forms
                              Electronic FormsInsurance
                              Drag & drop form builder

                              Notification Emails for FormsAlternativesSecurity & Compliance
                              Holiday FormsGoogle Forms alternative GDPR
                              Form to PDFJotform alternativeHIPAA Forms
                              Email FormsWufoo alternativeEncrypted Forms
                              Accessible FormsTypeform alternativeSecure Forms

                              WCAG

                                          Create. Review. Publish.

                                          Write, edit, collaborate on, and publish documents to different content management platforms.

                                          Get Started Now






                                                            You are currently viewing the help pages of Qntrl’s earlier version. Click here to view our latest version—Qntrl 3.0's help articles.




                                                                Manage your brands on social media

                                                                  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



                                                                    Zoho Sheet Resources

                                                                     

                                                                        Zoho Forms Resources


                                                                          Secure your business
                                                                          communication with Zoho Mail


                                                                          Mail on the move with
                                                                          Zoho Mail mobile application

                                                                            Stay on top of your schedule
                                                                            at all times


                                                                            Carry your calendar with you
                                                                            Anytime, anywhere




                                                                                  Zoho Sign Resources

                                                                                    Sign, Paperless!

                                                                                    Sign and send business documents on the go!

                                                                                    Get Started Now




                                                                                            Zoho TeamInbox Resources





                                                                                                      Zoho DataPrep Demo

                                                                                                      Get a personalized demo or POC

                                                                                                      REGISTER NOW


                                                                                                        Design. Discuss. Deliver.

                                                                                                        Create visually engaging stories with Zoho Show.

                                                                                                        Get Started Now










                                                                                                                              Wherever you are is as good as
                                                                                                                              your workplace

                                                                                                                                Resources

                                                                                                                                Videos

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



                                                                                                                                eBooks

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



                                                                                                                                Webinars

                                                                                                                                Sign up for our webinars and learn the Zoho CRM basics, from customization to sales force automation and more.



                                                                                                                                CRM Tips

                                                                                                                                Make the most of Zoho CRM with these useful tips.



                                                                                                                                  Zoho Show Resources