Your use case. Our milestone. The 200th post in our "Kaizen Series: Continuous Improvement for Developer Experience" is coming up. Share Now

X
Skip to product menu
close
  • Recent Launches
    Press Space or Enter to display list of options
EXPLORE ALL PRODUCTS

Recent Launches

New

Easy domain registration, transfer, and secured DNS management.

Try now
New

Payroll software with automated tax payments and filing.

Try now
New

Low-code IoT platform and solutions for connected businesses.

Try now
New

Business formation service to launch and grow your businesses.

Try now
New

Unified payment solution built for all businesses.

Try now
New

Comprehensive email security and archiving for every business.

Try now
Suites

Cloud-based qualitative data analysis tool.

Try now
New

Online community platform for individuals and businesses to grow their network and brand.

Try now
New

Modern retail POS to sell better, manage your entire business, and join the digital revolution.

Try now
SuitesNew

Unified project management platform for intelligent, data-driven work.

Try now
Suites

Unified platform for customer service and support teams.

Try now

Sales

CRM

Comprehensive CRM platform for customer-facing teams.

CRM
Voice

Cloud Contact Center Software for businesses.

Voice
Sign

Digital signature app for businesses.

Sign
Forms

Build online forms for every business need.

Forms
Bigin

Simple CRM for small businesses moving from spreadsheets.

Bigin
SalesIQ

Live chat app to engage and convert website visitors.

SalesIQ
Bookings

Appointment scheduling app for consultations with customers.

Bookings
RouteIQ

Comprehensive sales map visualization and optimal route planning solution.

RouteIQ
Thrive

Complete loyalty and affiliate management platform.

Thrive
Suites
CRM Plus

Unified platform to deliver top-notch customer experience.

CRM Plus

Marketing

Campaigns

Create, send, and track targeted email campaigns that drive sales.

Campaigns
Voice

Cloud Contact Center Software for businesses.

Voice
Sign

Digital signature app for businesses.

Sign
Forms

Build online forms for every business need.

Forms
Social

All-in-one social media management software.

Social
Survey

Design surveys to reach and interact with your audience.

Survey
SalesIQ

Live chat app to engage and convert website visitors.

SalesIQ
Sites

Online website builder with extensive customisation options.

Sites
Backstage

End-to-end event management software.

Backstage
PageSense

Website conversion optimization and personalisation platform.

PageSense
Marketing Automation

All-in-one marketing automation software.

Marketing Automation
LandingPage

Smart landing page builder to increase conversion rates

LandingPage
Webinar

Webinar platform for webcasting online webinars.

Webinar
NEW
LeadChain

Sync, manage, and convert leads across channels seamlessly.

LeadChain
NEW
Domains

Easy domain registration, transfer, and secured DNS management.

Domains
NEW
CommunitySpaces

Online community platform for individuals and businesses to grow their network and brand.

CommunitySpaces
Thrive

Complete loyalty and affiliate management platform.

Thrive
Publish

Manage all your local business listings on a single platform.

Publish
Suites
Marketing Plus

Unified marketing platform for marketing teams.

Marketing Plus

Commerce and POS

Commerce

eCommerce platform to manage and market your online store.

Commerce

Service

Desk

Helpdesk software to deliver great customer support.

Desk
Assist

Remote support and unattended remote access software.

Assist
Voice

Cloud Contact Center Software for businesses.

Voice
SalesIQ

Live chat app to engage and convert website visitors.

SalesIQ
Bookings

Appointment scheduling app for consultations with customers.

Bookings
FSM

End-to-end field service management platform for service businesses.

FSM
Lens

Interactive remote assistance software with augmented reality.

Lens
Solo

The all-in-one toolkit for solopreneurs.

Solo
Suites
Service Plus

Unified platform for customer service and support teams.

Service Plus

Finance

Books

Powerful accounting platform for growing businesses.

Books
Expense

Effortless expense reporting platform.

Expense
Sign

Digital signature app for businesses.

Sign
Inventory

Powerful stock management and inventory control software.

Inventory
FREE
Invoice

100% Free invoicing solution.

Invoice
Billing

End-to-end billing solution for your business.

Billing
NEW
Payroll

Payroll software with automated tax payments and filing.

Payroll
Commerce

eCommerce platform to manage and market your online store.

Commerce
Checkout

Collect payments online with custom branded pages.

Checkout
Practice

Practice management software for accounting firms.

Practice
Solo

The all-in-one toolkit for solopreneurs.

Solo
NEW
Payments

Unified payment solution built for all businesses.

Payments
Suites
Finance Plus

All-in-one suite to manage your operations and finances.

Finance Plus

Email, Storage, and Collaboration

Mail

Secure email service for teams of all sizes.

Mail
Voice

Cloud Contact Center Software for businesses.

Voice
Sign

Digital signature app for businesses.

Sign
WorkDrive

Online file management for teams.

WorkDrive
Bookings

Appointment scheduling app for consultations with customers.

Bookings
Cliq

Stay in touch with teams no matter where you are.

Cliq
Notebook

Beautiful home for all your notes.

Notebook
Meeting

Online meeting software for all your video conferencing & webinar needs.

Meeting
Connect

Employee experience platform to communicate, engage, and build positive employee relations.

Connect
Learn

Knowledge and learning management platform.

Learn
Office Integrator

Built in document editors for web apps.

Office Integrator
Writer

Word processor for focused writing and discussions.

Writer
TeamInbox

Shared inboxes for teams.

TeamInbox
ZeptoMail

Secure and reliable transactional email sending service.

ZeptoMail
Show

Create, edit, and share slides with a sleek presentation app.

Show
Tables

Work management tool to connect people, processes, and information.

Tables
Sheet

Spreadsheet software for collaborative teams.

Sheet
Office Suite

Powerful collaborative work platform for teams.

Office Suite
Calendar

Online business calendar to manage events and schedule appointments.

Calendar
ToDo

Collaborative task management for individuals and teams.

ToDo
FREE
PDF Editor

Collaborative online PDF editing tool.

PDF Editor
Suites
Workplace

Application suite built to improve team productivity and collaboration.

Workplace

Human Resources

Expense

Effortless expense reporting platform.

Expense
Recruit

Intuitive recruiting platform built to provide hiring solutions.

Recruit
People

Organize, automate, and simplify your HR processes.

People
Sign

Digital signature app for businesses.

Sign
NEW
Payroll

Payroll software with automated tax payments and filing.

Payroll
Shifts

Employee scheduling and time tracking app.

Shifts
Workerly

Manage temporary staffing with an employee scheduling solution.

Workerly
Suites
People Plus

Comprehensive HR platform for seamless employee experiences.

People Plus

Security and IT Management

Creator

Build custom apps to simplify business processes.

Creator
Assist

Remote support and unattended remote access software.

Assist
Vault

Online password manager for teams.

Vault
Directory

Workforce identity and access management solution for cloud businesses.

Directory
Lens

Interactive remote assistance software with augmented reality.

Lens
QEngine

Test automation software to build, manage, execute, and report testcases.

QEngine
Catalyst

Pro-code platform to build and deploy your apps.

Catalyst
RPA

Automate manual, tedious, and repetitive tasks easily.

RPA
NEW
eProtect

Comprehensive email security and archiving for every business.

eProtect
FREE
OneAuth

Secure multi-factor authenticator (MFA) for all your online accounts.

OneAuth
Toolkit

Complete resource for any admin-related lookup queries.

Toolkit

BI and Analytics

Analytics

Modern self-service BI and analytics platform.

Analytics
DataPrep

AI-powered data preparation service for your data-driven organization.

DataPrep
NEW
IoT

Harnessing IoT analytics for real-time operational intelligence.

IoT
Embedded BI

Embedded analytics and white label BI solutions, tailored for your needs.

Embedded BI

Project Management

Projects

Manage, track, and collaborate on projects with teams.

Projects
Sprints

Planning and tracking tool for scrum teams.

Sprints
BugTracker

Automatic bug tracking software for managing bugs.

BugTracker
Solo

The all-in-one toolkit for solopreneurs.

Solo
Suites
Projects Plus

Unified project management platform for intelligent, data-driven work.

Projects Plus

Developer Platforms

Creator

Build custom apps to simplify business processes.

Creator
Flow

Automate business workflows by creating smart integrations.

Flow
Office Integrator

Built in document editors for web apps.

Office Integrator
DataPrep

AI-powered data preparation service for your data-driven organization.

DataPrep
ZeptoMail

Secure and reliable transactional email sending service.

ZeptoMail
Tables

Work management tool to connect people, processes, and information.

Tables
QEngine

Test automation software to build, manage, execute, and report testcases.

QEngine
Catalyst

Pro-code platform to build and deploy your apps.

Catalyst
RPA

Automate manual, tedious, and repetitive tasks easily.

RPA
NEW
IoT

Build, deploy, and scale IoT solutions for connected businesses.

IoT
Apptics

Application analytics for all apps.

Apptics
Embedded BI

Embedded analytics and white label BI solutions, tailored for your needs.

Embedded BI

IoT

NEW
IoT

Low-code IoT platform and solutions for connected businesses.

IoT

Search Result

CRM Plus

Unified platform to deliver top-notch customer experience.

Try now
CRM Plus
Service Plus

Unified platform for customer service and support teams.

Try now
Service Plus
Finance Plus

All-in-one suite to manage your operations and finances.

Try now
Finance Plus
People Plus

Comprehensive HR platform for seamless employee experiences.

Try now
People Plus
Workplace

Application suite built to improve team productivity and collaboration.

Try now
Workplace
Marketing Plus

Unified marketing platform for marketing teams.

Try now
Marketing Plus
Projects Plus

Unified project management platform for intelligent, data-driven work.

Try now
Projects Plus
All-in-one suite

Zoho One

The Operating System for Business

Run your entire business on Zoho with our unified cloud software, designed to help you break down silos between departments and increase organizational efficiency.

TRY ZOHO ONE
Zoho Marketplace

With over 2000 ready-to-use extensions across 40+ categories, connect your favorite business tools with the Zoho products you already use.

EXPLORE MARKETPLACE
Skip to main content

Best Practices of Client Script

Follow the below best practices for better Client Scripting.

1. Use Static Resources for repeated scripts

If you want to use the same script on multiple pages for multiple events, upload the code as a static resource , add the static resource to Client Script, and reference it in the script.

Consider that you want to validate the SSN Number. If you have the same requirement or functionality in multiple layouts or multiple pages of the same module or in multiple modules, you can use a single line of script instead of repeating the same set of code across multiple Client Scripts. This way we can achieve reusability of code using static resources. 

Js file:


function is_socialSecurity_Number(str) { 
regexp = /^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$/;
if(regexp.test(str)) { 
return true; } 
else { 
return false; 
 } }

Create a Javascript file and upload the above static file, and add the static file to the Client Script. Refer to Static Resources for more information. You can call the method from the static resource and use them in your script as shown in the below script.


//Get the field value that has to be validated
var ssn = ZDK.Page.getField("SSN");
//*Check if the value is a valid SSN using function in js file.*/
if(is_socialSecurity_Number(ssn))
{
//If it is a valid SSN, display confirmation box that "The lead details are validated". 
ZDK.Client.showConfirmation('The lead details are validated');
 }
else
{
//If it is not a valid SSN, display error message that " The lead values are not validated". 
ZDK.Client.showMessage('The lead details are not validated', { type: 'error'
 });
 }

Note:

You can upload only up to 5 static resources for a particular page.

 

2. Use the available arguments of event types in your script

Refer to the below table to know the arguments that can be used inside the script for a particular event type.

PageEvent TypeEvent NameArguments
Clone Page / Edit PagePageonChangefield_name
onLoad__
onSave__
FieldonChangevalue
Detail Page (Canvas)PageonLoad__
FieldonBeforeUpdatevalue
Mandatory Fields FormonBeforeMandatoryFormSavevalue
onMandatoryFormLoadfield
Blueprint EventbeforeTransitiontransition
Tag EventonTagChangedtag, added and removed
CanvasonClick__
IcononClick__
TextonClick__
Create PagePageonChangefield_name
onLoad__
onSave__
FieldonChangevalue
Detail Page (Standard)PageonLoad__
FieldonBeforeUpdatevalue
Mandatory Fields FormonBeforeMandatoryFormSavevalue
onMandatoryFormLoadfield
Blueprint EventbeforeTransitiontransition
Tag EventonTagChangedtag, added and removed
List Page (Standard)Page EventonCustomViewLoadcustom_view
onBeforeCustomViewChangecustom_view
Create Page (Wizard)Wizard EventonLoad__
onChangefield_name
onTransitionscreen
onBeforeTransitionsource_screen, target_screen
onBeforeSave__
Field EventonChangevalue
Edit Page (Wizard)Wizard EventonLoad__
onChangefield_name
onTransitionscreen
onBeforeTransitionsource_screen, target_screen
onBeforeSave__
Field EventonChangevalue

For example, value is the argument for field onChange event type and so the Client Script will hold the value of that field in value. You can just use value instead of ZDK.Page.getField("field_name").getvalue();

3. For multiple actions on the same page, create a single script with 'If' or 'Switch' conditions

In the case of multiple field events on the same page, you can create a single script with an if or switch.. case statement to check which field is updated.

For example, to add validation for fields Product, Phone Number, Country, and Category in create page you can create four Client Scripts on create page with field events for each of the fields separately. But it is a best practice to create one Client Script on create page with onChange page event instead of multiple Client Scripts. In page event, you can use conditions to check which field is being changed and add actions inside those conditions. Below is the sample script which has multiple conditions for multiple fields.


switch (field_name) 
{ 
case 'Product': 
var product_name = ZDK.Page.getField('Product').getValue(); 
var category_field = ZDK.Page.getField('Category'); 
if (['Sparking cable', 'Ignition box', 'Ignition coil', 'Spark plug'].includes(product_name)) { 
category_field.setValue("Ignition system"); ZDK.Page.getField('Number_of_Boxes').setMandatory(true); } 
else  if (['Speedometer', 'Odometer', 'Voltmeter', 'Temperature gauge'].includes(product_name)) {  category_field.setValue('Gauges and meters'); } 
break;    
case 'Phone_Number': 
var phone_field = ZDK.Page.getField('Phone_Number'); 
if (phone_field.getValue().length < 10) { 
phone_field.showError('Enter a valid phone number'); } 
break;
case 'Country':
ZDK.Page.getField('Phone_Number').setMaxLength(10); break; 
case 'Category': 
if(ZDK.Page.getField('Category').getValue() === 'Ignition system') { ZDK.Page.getField('Number_of_Boxes').setMandatory(true); } 
break; }

Note:

You can create up to 30 Client Scripts per page.

4. Debug using log statements

Use the log statement to debug the script wherever required and run the script using the Run option in Client Script IDE. The logs will be available in the Messages panel of Run option. Here is the screenshot of how you can add log statements in your script and where you can see the logs when the script executes.

log-satement.png

log-messages.png

5. Use the Terminal to try out ZDKs

Whenever you want to try our ZDKs instantly, you can do it in the Terminal Section available in the Run option of Client Script IDE. For example, when you type the below script in the Terminal section and hit enter, you can see the alert message on the screen.

ZDK.Client.showMessage('Test ZDK Functionality using Terminal section', { type: 'info' });

terminaltest.png

6. Create separate scripts for each layout

Client Scripts will execute only for the layout you specify while configuring the Client Script. If you want the script to execute for other layouts or all the layouts of a module, you should create a separate script for each layout.

7. Whitelist API calls

Make sure that the API calls from a Client Script to other domains are whitelisted in Trusted Domains.

For instance, consider that you want to populate the field Distance with the distance between the Seller Location and the Manufacturer Location fields. In order to achieve this you can write a script onChange page event.

Script:


//Check if the Location fields are updated
if (field_name === "Seller_Location" || field_name === "Manufacturer_Location") {
//Assign the third party API key to a variable
var api_key = "2Ty9CbowZU8Nu3pl3LQb*********";
//Assign the field "Distance" to a variable
var distance = ZDK.Page.getField("Distance");
//Make the field "Distance" read-only.
distance.setReadOnly(true);
//Get form values
var formObj = ZDK.Page.getForm(); var form = formObj.getValues();
if (form.Manufacturer_Location && form.Seller_Location) {
/*Third party API call with the Location fields values. The domain of the API call should be added to Trusted Domains of Zoho CRM */
var response = fetch("https://api.***/maps/api/dist**/json?origins="+form.Manufacturer_Location+"&destinations="+form.Seller_Location+"&key="+api_key);
//Populate the response in the "Distance field".
response.then(res => res.json()).then(data => { distance.setValue(data.rows[0].elements[0].distance.text); });
}
 }

The script will be able to get the response successfully only if the API calls to the domain used is whitelisted in Trusted Domains. Click here to know how to whitelist third party API calls.

8. Use reorder option to change the order of scripts

Whenever you want to change the order of execution of Client Scripts for a particular page and a particular event, use the Reorder button available in the Client Script Screen.

new_img

Remember that the order change is applicable only within a particular event for a particular page in a module.

9. Use the right event type for your requirement

  • To perform validations before the record is saved, use onSave Page Event. So that after entering data for all fields, when the user hits on the save button, the script will get executed.
  • To perform validation as soon as data is entered on a particular field use onChange Field Event.
  • To perform validation as soon as data is entered for multiple fields use onChange Page Event.
  • If you want to display a custom message/ Information box whenever a page is opened, use onLoad Page Event.

10. Use Loaders to Manage Timeout Limits

In Client Script, executions are bounded by a 10-second time out. Some API calls might take more than 10 seconds to provide response. Consequently, when they are used in Client Script, execution will get halted. In such cases, you can show a loader which will pause the execution until you receive the response from the API call. 
Consider the following scenario.
Whenever the user changes the stage to 'Delivered' in the Quotes Module, a Client Script gets triggered. This script, in turn, executes a function, and this function takes more than 10 seconds to complete.

In this case, you can show a loader preceding the function's execution, after which you should hide it.

Script:


 if (value == 'Delivered') {
ZDK.Client.showLoader({type:'page', template:'spinner', message:'Sending Quotation...' });
ZDK.Apps.CRM.Functions.execute("Send_Quote");
ZDK.Client.hideLoader();
ZDK.Client.showMessage('Quotation sent successfully', { type: 'success' });
}

Here is how the Client Script works.

The presence of loader on the screen will inform the user about the ongoing processes in the background.