Kaizen #99 - Render Widgets Using Client Script

Kaizen #99 - Render Widgets Using Client Script

Hello everyone!
Welcome back to another interesting post. In this post, let us see how you can render Widgets using Client Script.

Widgets are embeddable UI components that you can create and add to your Zoho CRM. You can use widgets to perform functions that utilize data from third-party applications. You can build widgets for Zoho CRM using our JS SDK.

You can render a Widget through Client Script and pass data from the Widget to the Client Script.

Use Case:
At Zylker, a manufacturing company, the Service Agent places orders using the Orders module.  There is a sub-form named Product list. The user should add the products by clicking the "Add row" button every time. 



To avoid this, Zylker wants the users to select multiple products from a single pop-up. Once the user selects the products from that pop-up , the sub-form "Product list" should get updated with all those products(one product in one sub-form row).

Solution:

Whenever the user picks the Product Category, you can create a Client Script to render the widget. The Products selected by the user on the widget , will be passed to the Client Script and will be added as separate rows in  Product list subform.
 
1. Install Zoho CLI and add code to the app folder.
2. Upload the zip file as a Widget.
3. Create a Client Script to render the Widget and to add data to the Sub-form.


1.  Install Zoho CLI and add code to the app folder 

Follow the steps given in this post and add the html code, javascript file and css file.

Index.html



<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Choose products</title>
  <link href="styles/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <div class="wgt_cp_popupContent">
    <section class="wgt_cp_contentWrap">
      <div hidden="true" id="noProductDiv">
        <pre>No products associated to the selected deal</pre>
      </div>
      <table width="100%" cellspacing="0" id="pTable">
        <thead>
          <tr class="wgt_productTblHead">
            <th><input type="checkbox" id="selectAll"     onclick="selectAllProducts(this)"></th>
            <th>Product Name</th>
            <th>Product Category</th>
            <th>Unit Price</th>
            <th>Quantity in Stock</th>
          </tr>
        </thead>
        <tbody id="tbody"></tbody>
      </table>
    </section>
  </div>
  <script src="./script/script.js"></script>
</body>
</html>


Script.js

var count = 0;
var productData, maxRows = 0;
ZOHO.embeddedApp.on("PageLoad", async function (data) {
 console.log("data from Client Script", data);
 maxRows = data.max_rows;
 const search_response = await ZOHO.CRM.API.searchRecord({ Entity: "Products", Type: "criteria", Query: "(Product_Category:equals:" + data.product_category + ")" })
 if (search_response && search_response.data && search_response.data.length) {
  productData = search_response.data;
  var htmlString = "";
  productData.forEach(({ id, Product_Category, Product_Name, Unit_Price, Qty_in_Stock }) => {
   htmlString = htmlString.concat(
    `<tr>
     <td><input type='checkbox' onclick='selected(this)' id='${id}' class='products'></td>
     <td>${Product_Name}</td>
     <td>${Product_Category}</td>
     <td>${Unit_Price}</td>
     <td>${Qty_in_Stock}</td>
    </tr>`
   );
  });
  document.getElementById("tbody").innerHTML = htmlString;
 } else {
  document.getElementById("pTable").hidden = true;
  document.getElementById("noProductDiv").hidden = false;}
});
ZOHO.embeddedApp.init();
function selected(element) {
 element.checked ? count++ : count-- ;
 document.getElementById("selectedCount").innerHTML = `${count} Products selected`;
}
function closewidget() {
 if (count > maxRows) {
  alert("Selected product is greater than the maximum subform rows.");
 } else {
  var selected_products = [];
  for (product_element of document.getElementsByClassName('products')) {
   product_element.checked && selected_products.push(productData.find(product => product.id === product_element.id));}
  console.log("returning to Client Script ...", JSON.stringify(selected_products));
  $Client.close(selected_products);}
}


As per the above script, the products are fetched from the "Products" module based on the "Product Category" selected by the user. This information is captured in "search_response" and is added to the body of  widget.html
Here,  the code $Client.close(selected_products); will pass the selected products from Widget to the Client Script and close the widget rendered from Client Script. Click here for more details about the variable $Client.
Next step is to upload the zip file of the app folder.
Click here to view the complete code.

2. Upload the zip file as a Widget
  • Go to Setup > Developer Space > Widgets.
  • Click Create New Widget.

  • The Hosting should be "Zoho" and mention the html page of the app folder that you uploaded.
Note: The widget should be of "button" type in order to render through a Client Script.

3. Create a Client Script to render Widget and to add data to the subform
  • Go to Setup > Developer Space > Client Script. Click +New Script.
  • Specify the details to create a script and click Next.
  • The Client Script should render the Widget when the user selects Product Category. So Client Script should have field event on the field "Product Category".
  • On the Client Script IDE, you can see the below details.

  • Enter the following script in the Client Script IDE and click save.

var products_list = ZDK.Page.getField('Product_list').getValue();
if (products_list.length === 1) { // Clear subform if empty row
    !Object.values(products_list[0]).every(value => !!value) && products_list.pop();
}
// Open widget with product category & max. allowed rows based on existing subform data
var selected_products = ZDK.Client.openPopup({
    api_name: 'choose_products', type: 'widget', header: 'Choose Products', animation_type: 1, height: '570px', width: '1359px', left: '150px'
}, {
    product_category: value, max_rows: 25 - products_list.length
});
// Update subform with Selected Products from the widget Popup
if (selected_products.length) {
    selected_products.forEach(product => {
        products_list.push({ Product_Name: { id: product.id, name: product.Product_Name }, Quantity: 1, Unit_Price: product.Unit_Price });
    });
  ZDK.Page.getField('Product_list').setValue(products_list);
}


  • To render a widget from Client Script, use openPopup(config, data)  ZDK. You can specify the configuration details like api name of the widget, title, size, animation type as parameters and specify the data to be passed as 'PageLoad' event data in the Widget. 
  • The response from the widget (i.e user selection) is captured by the variable "selected_products". Then each product (id,name,product_name,quantity and unit_price) is pushed to the list products_list. Finally, the product list value  is updated to the Product Category sub-form using setValue(value) ZDK. 
  • Here is how the Widget gets rendered through Client Script.



We hope you found this post useful. We will meet you next week with another interesting topic! If you have any questions let us know in the comment section.

Click here for more details on Client Script in Zoho CRM.


As we approach the 100th post in our Kaizen series next week, we invite you to share your queries and concerns with us.  We are always looking for ways to improve our content and make it more relevant to our readers.

Please fill out this form to share your thoughts.




Happy Coding!




    • Sticky Posts

    • Kaizen #217 - Actions APIs : Tasks

      Welcome to another week of Kaizen! In last week's post we discussed Email Notifications APIs which act as the link between your Workflow automations and you. We have discussed how Zylker Cloud Services uses Email Notifications API in their custom dashboard.
    • Kaizen #216 - Actions APIs : Email Notifications

      Welcome to another week of Kaizen! For the last three weeks, we have been discussing Zylker's workflows. We successfully updated a dormant workflow, built a new one from the ground up and more. But our work is not finished—these automated processes are
    • Kaizen #152 - Client Script Support for the new Canvas Record Forms

      Hello everyone! Have you ever wanted to trigger actions on click of a canvas button, icon, or text mandatory forms in Create/Edit and Clone Pages? Have you ever wanted to control how elements behave on the new Canvas Record Forms? This can be achieved
    • Kaizen #142: How to Navigate to Another Page in Zoho CRM using Client Script

      Hello everyone! Welcome back to another exciting Kaizen post. In this post, let us see how you can you navigate to different Pages using Client Script. In this Kaizen post, Need to Navigate to different Pages Client Script ZDKs related to navigation A.
    • Kaizen #210 - Answering your Questions | Event Management System using ZDK CLI

      Hello Everyone, Welcome back to yet another post in the Kaizen Series! As you already may know, for the Kaizen #200 milestone, we asked for your feedback and many of you suggested topics for us to discuss. We have been writing on these topics over the
    • Recent Topics

    • Migrating Shopify Customers and Tags to Zoho Commerce

      I’m exploring options for migrating our existing Shopify customer accounts into the Zoho Commerce member portal. Specifically, I have a few questions: API Availability: Is there a public API or supported endpoint that allows us to import Shopify users
    • Multilingual website feature

      Would be a great feature to have. I saw that this feature was available for backstage. I think it could be done for zoho sites too.
    • How Can i Add Email campaign for my UAEVisaOnline.center website

      Hello Team, i want to create email campaign for our website https://www.uaevisaonline.center but can't able to add. Its showing error like please try after some time. Can you please help and solve the issue. Thanks!
    • The domain Etihaduaevisa.com which you have entered belongs to a different deployment/region

      Hi Team, I am trying to set up a business email account to Zoho for www.etihaduaevisa.com but it doesn't allow me There is a message that pops out The domain which you have entered belongs to a different deployment/region Kindly assist me with this. Thank
    • Outlook not recognising Zoho Inbound server

      I have been receiving my ZOHO emails using MS Outllok on my iPhone and PC, but since Friday 2nd May, incoming emails are not arriving via Outlook and I get the error message saying the server is 'not responding'. Have ZOHO changed the settings for the
    • Zoho Sign / CRM integration - stop unsigned documents being attached

      I'm using the the CRM/Sign integration to send documents for signature from Zoho CRM. I noticed that an unsigned copy of the document is added as an attachment in the CRM. Is there a way to stop this? I only want signed documents to be attached. The unsigned
    • Resend invite

      Hi, How do I resend an invitation to someone who didn't get the invite the first time around? I tried going to Setup-->User (like it says in the Help) but there was no option to resend. It doesn't display any users who has not accepted the invitation.
    • Asking for implementation roadmap or step-by-step guidelines

      Hello everyone, I'm a freelancer who's been hired to implement Zoho CRM for a client, and I want to make sure I approach this correctly. Could someone kindly share a comprehensive implementation roadmap or step-by-step guide that covers all the essential
    • Asking for implementation roadmap or step-by-step guidelines

      Hello everyone, I'm a freelancer who's been hired to implement Zoho CRM for a client, and I want to make sure I approach this correctly. Could someone kindly share a comprehensive implementation roadmap or step-by-step guide that covers all the essential
    • Approval Workflow for Purchase Orders Abrir

      The requirement is , that all purchase orders greater than or equal to 5000 go through an approval process from certain people, but within books I only see that the approvers can be by levels or any approver but we cannot enter a rule like these. Can
    • Multiple subforms from same existing form

      Hello, In an Order form, I have a subform for Line items. But my items have 5 distinct product categories. To make it pleasant and easy to use, I want to repeat the subform 5 times in the same parent form, to separate my 5 categories of product. But I
    • Announcement: Zoho DataPrep 1.0 will be deprecated on January 31, 2026

      We'd like to inform you that the Zoho DataPrep 1.0 version will be officially deprecated as of January 31, 2026. This aligns with our efforts to streamline and improve your overall experience with Zoho DataPrep 2.0 which was released in Sep 2024 . To
    • Discussions from Ask the Experts 19 : Inside Zoho Desk Spring Release 2025

      Hello Everyone, We appreciate the engaging discussions during the Ask the Experts 19 session on the Spring Release. It was a pleasure connecting with you. Our team is actively working towards your requests to deliver an improved experience. In this post,
    • Optimisez la gestion des bots et la conformité à Apple MPP

      Filtrage des bots : une nécessité pour des données marketing fiables Les indicateurs de performance sont au cœur de toute stratégie marketing. Cependant, l’augmentation du trafic généré par des bots ainsi que l’adoption croissante de fonctionnalités comme
    • One time batch workflow to repair omission of data

      Hi, I created a parent form (Product) and another form (Prices) that is used as subform in the parent form. In the parent form I have a field Category that must appear in the subform, but I forgot to create the field at first in the subform and now I
    • Advance Your Churn Predictions with Zia's Usage Data Feature: Event Mapping

      Greetings all, This is an important and exciting update about feeding usage data into Zoho CRM. To expand the scope of how usage data can be used by Zia, we are introducing a new section called Usage Data under Zia. Users can now easily import, edit,
    • Web-To-Quote form would be awesome

      It would be awesome to be able to embed a quote form on a website and have that filter in to Zoho CRM. Account Number to match the Account in Zoho Email address could match the Contact. Product Code could be required to match the product. Not sure about quantity? I am sure this all could probably be done via the API and maybe some middleman interaction with Creator, but it would be nice if it was as easy as the Web-to-Case form. Something like this could lead to further integration with CMS and Shops
    • Published Sheet - Share option to show "Save copy to WorkDrive"

      Hi Sheets Team, I'm currently working on a Zoho Sheet which I want to share with other Zoho users outside of my organisation. Normally I would do this with Google Sheets but I'm trying to make better use of my Zoho tools. When I share a Google Sheet publicly
    • Bills vs. Expenses

      Hi eveyone, Can somebody explain me a little bit better of how can I use Bills and Expenses in my business? I don’t understand their differences to be honest.
    • Integration to LinkedIn Recruiter

      We'd like you to support Recruiter System Connect to sync our LinkedIn Recruiter candidates to the Zoho Recruit ATS. How can we do this?
    • List View just got a makeover!

      Hello everyone, The new list view is being rolled out in phases and will be available to all our users by the end of January 2021. We are excited to announce that the list view in modules is set to get a new look. The new list view is sleek, contextual,
    • Add Video block needs improvement

      I regularly send out links to videos in my campaigns and I find that built in video block is never good enough to use in my campaigns, so I have to make a thumbnail in Canva and upload it or screenshot the actual video on YouTube. The concept of the video
    • Profile cannot add tasks, calls or meetings

      Good morning, I have a Profile of users that's called "Standard2" and their module permissions are set as follows: Despite this, one of my users on the Standard2 profile gets this when they try to add a call: Any idea how to fix this? If i bump them up
    • Zoho Developer Community Monthly Digest – April 2025

      Hello everyone, Welcome to this month’s Zoho Developer Community Digest! We’ve lined up an exciting series of technical sessions, product deep-dives, and community conversations to keep you informed and inspired. Don’t forget to check out our resource
    • Dataprep est-ce que zoho est sérieux ??

      Nous venons encore de passer plus de 2 heures avec le support zoho qui est incapable de résoudre le problème rencontré dans la mise en place d'un pipeline de données entre le C>>RM et DataPrep Celà fait 5 mois que nous essayons de faire fonctionner le
    • STOCK COUNT - How is this even possible

      Dear Zoho One, We have a lot of products from Zoho but I really don't understand this. We mainly use ZOHO FSM with ZOHO INVENTORY because we are in service and maintenance for electric charging stations for cars All employees of Zoho FSM have their own
    • Changing sequence of buttons

      How can I change the sequence of these buttons? I want the 'Versturen referral campagne' to be displayed as the default button
    • Unapproved Articles for Review?

      What is this feature and how do I use it? I'm not seeing any option to mark articles as unapproved and needing review.
    • Trying to fetch related list data from deals module

      I need to fetch stage history data which comes in related list in deals module using coql. How can I achieve that? { "select_query": "SELECT Technical_Survey_Date as system_order_confirmation_date, Stage,Created_By, Latest_Quote_Creation_Date,Originating_Source,
    • Stage-Probability Mapping

      How do I answer this question in analytics? What is the Closed-Won percentage of all Deals that reach a given stage? Another way: Of all Deals that reach a given stage (eg. Artwork/Price Quote), what percentage of them become Closed-Won? I want to populate
    • Follow-up Sequences

      For following up with leads based on open/click status.
    • How do I change the sort order of items in the User Filter?

      I have a chart for which I have set a custom sort order for a field. I noticed that in the user filter for this field, the order is shown as alphabetical. It does not reflect the custom sorting that I configured. I even tried selecting the checkbox "Make
    • Automate Zoho Projects Task Data Export and Email Delivery (for Non-Users)

      In many real-world scenarios, we need to share Zoho Projects task updates with clients or team members who don’t use Zoho or don’t have access to the platform. Since there’s no built-in way to export and email tasks directly within Zoho Projects, I put
    • Bulk Add notes

      I think that it's an absolute need and basic feature to add. I know we can import notes from an xls spreasheet, but that's not what I'm talking about. We should be able the same way that we can bulk send email, bulk add activities, we should be able to
    • How to use CRM custom button and client script?

      Here's what I need. I know how to handle each step in isolation. I do not understand how to intercept a Button interaction, pass it to the client-script for the user prompt, and remainder of the processing. User Clicks Button on Details Page Client-Side
    • Match one bank transaction to multiple customer with TDS dedcuction

      Hi team, Just wanted to know. How can i match one bank entry to multiple customer invoices with tds.
    • Zoho Product Sync between Books and CRM is a mess

      The syncing of products between Zoho Books and CRM is completely broken. Why is ZOHO CRM the center of all products? Surely it should be Books or Inventory that is the central focal point of all things to do with a business backend (i.e. not marketing
    • How can i resend a campaign to only one of the recipients on the original campaign

      How can i resend a campaign to only one of the recipients on the original campaign ? Sincererly, Mike
    • Zoho Campaign low open rate

      I have been using Zoho One, Zoho CRM and Zoho Campaign to make my web application, but since I started using zoho campaign to send emails, it has low open rate (actually zero for the latest campaign for 2 days) For people who have more experience or know
    • More Workflow Triggers

      We utilize a lot of workflows in our organization. Recently we've identified two use cases where we would like a workflow to run a function. Upon further checking, the workflow trigger wasn't available, or the only option was to run the workflow more
    • Next Page