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!




    • Recent Topics

    • Kaizen# 209 - Answering Your Questions | All About Client Script

      Hello everyone! Welcome back to another exciting Kaizen post! Thanks for all your feedback and questions. In this post, let's see the answers to your questions related to Client Script. We took the time to discuss with our development team, carefully
    • Unable to copy into a new document

      Whe I create a new Writer doc and attemp to copy and past I get this message. The only way to copy into a document is I duplicate an existing document, erase the text and save it under a different name and then paste the information. Not ideal. Can you
    • To Do: shareable task links without login

      Hi! I’m using Zoho Mail and ToDo in my daily work, and I’ve run into one limitation that’s a real blocker for me. Right now, to share tasks with managers or directors, they need to have a Zoho account and be added to a group. In practice, many of them
    • Ability to turn off "Would you like this amount to be reflected in the Payment field?" message

      Team, Is there any way to turn off the message" Would you like this amount to be reflected in the Payment field?" when I make a payment? This is so annoying. This happens EVERY TIME I put an amount in the Payment Made field.
    • Two currencies

      More and more I am finding that internattional payments' fees are unpredictable. I would like, on my invoices that are in a foreign currency (eg. USD$ or EUR€) for there to be a GBP£ TOTAL display alongside the invoice's currency total. This would make
    • Massive spam pretending to come from our address – is this a Zoho security issue?

      Hi, We’ve been receiving more and more suspicious emails lately — many of them clearly look like scams. But yesterday, we got an email that appeared to be sent from our own address, which was very concerning. We're starting to wonder if this might be
    • Unlock agreement intelligence with Zoho Sign's latest AI updates

      Hello! If you've been struggling with long, complex agreements and spending way too much time on them, here's exactly what you'll want to hear: Zoho Sign now integrates with OpenAI's ChatGPT to make agreement management smarter and simpler. Acting like
    • Currency abbreviations

      Hello, Im stuck, and need help. I need the currency fields for example, opportunity value, or total revenue, to be abbreviated, lets say for 1,000 - 1K, 1,000,000 - 1M, and so on, how should I do this?
    • Embed Sign Document

      Has anyone tried embedding a document in a webpage? I'm building a webpage (using PowerPage) and I'm trying to embed it using an iframe then I got this error: Refused to display 'https://sign.zoho.com/' in a frame because it set 'X-Frame-Options' to
    • Zeptomail API error 500 internal server error

      Hi Everyone, getting this eror continuously! Can anyone please guide around the same! Zeptomail API error 500 internal server error Best Regards
    • We’re transitioning from Zoho ShowTime to TrainerCentral

      Hello everyone, Zoho ShowTime was originally built as a training platform to serve training agencies, HR teams, and individual trainers. As the platform grew, we realized that more creators and businesses could benefit from its capabilities. That’s why
    • Emails Are Not Being Delivered to My Inbox

      Hello Zoho Support Team, I am experiencing an issue with my Zoho Mail account. The most important problem is that emails are not being delivered to my inbox. Details: My Zoho Mail address: info@coreforcelife.com What happens: I am not receiving any incoming
    • Upload my theme.

      Hello. I would like to upload my own theme, this one: https://themeforest.net/item/panagea-travel-and-tours-listings-template/21957086 Is it compatible and where I upload it? If not I will hire a developer, what do I have to ask when I search for one?
    • Radar In Focus: Track customer support metrics using Radar's static reports

      Hello everyone, Welcome back to the Radar In Focus series, where we explore how Radar features can add value to your business. In this episode, we're looking at Radar static reports. The help desk is filled with vast amounts of data that can be analyzed
    • Mail ToDo & Tasks Webhooks

      Our company uses Zoho ToDo inside Mail to manage our tasks. When I create a task and assign it to a team member it does not notify them unless I add a reminder via mail. I'm trying to create a webhook for when a task is created to send a cliq message
    • Allocating inventory to specific SO's

      Is there a way that allocate inventory to a specific sales order? For example, let's say we have 90 items in stock. Customer 1 orders 100 items. This allocates all 90 items to their order, and they have a back order for the remaining 10 items which could
    • Improved UI for a Seamless User Experience - Calls, Tasks, and Meetings

      Hello all, We are making UI unification across CRM so that the UI experience is seamless across the product. As part of that effort, we have made changes to the details page of activity-based module records—Meetings, Calls, and Tasks. Let's look at these
    • Where can I find rejected inbound mails and their reason for rejection

      Hi, I was recently made aware by a mailing list which I am subscribed to (ffmpeg-devel@ffmpeg.org) that my Zoho mail Mail account is rejecting some emails. If I look under Admin Panel > Security & Compliance > Quarantine > Incoming, the list there is
    • Refund

      Hi There, Please refund me asap possible, because of no support given. Thank you
    • 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
    • تغيير عمله الدفع"Change payment currency"

      ما هى طريقه تغيير عمله الدفع "ما هي طريقة تغيير عملة الدفع؟"
    • How do I fix this? Unable to send message; Reason:554 5.1.8 Email Outgoing Blocked.

      How do I fix this? Unable to send message; Reason:554 5.1.8 Email Outgoing Blocked.
    • Attention API Users: Upcoming Support for Renaming System Fields

      Hello all! We are excited to announce an upcoming enhancement in Zoho CRM: support for renaming system-defined fields! Current Behavior Currently, system-defined fields returned by the GET - Fields Metadata API have display_label and field_label properties
    • Zia's ability to generate and improve content extended to Desk mobile app (iOS and Android)

      In support, agents will have to understand customers' pain points completely to provide empathetic personalized solutions and a positive experience. However, at times, agents might find it challenging to comprehend the customer issues and connect with
    • BANK FEED - MAYBANK , provider from YODLEE IS NOT WORKING

      As per topic, the provider YODLEE is not working for the BANK FEED. It have been reported since 2023 Q3, and second report on 2023 Q4. now almost end of 2024 Q1, and coming to 2024 Q2. Malaysia Bank Maybank is NOT working. can anyone check on this issue?
    • Customer Grouping

      Hi, how can I group multiple customers into single group. So that I can have idea of accounts receivables of all the customers in single group. Like if there are multiple subsidiaries of same company we have having a business with, and want to view the
    • Item images

      Can we get an "On hover" expanded image for items please ?
    • Free webinar—Redefining workforce security with Zoho Vault: Passwords, passkeys, and multi-factor authentication

      Hi everyone! Did you know that in Q2 alone, 94 million data records were leaked globally? Behind every breach is a combination of poor password habits, phishing attacks, privilege misuse, and simple human error. The fallout—including reputational damage,
    • Zoho Sign product updates - Q3 2025

      Hello everyone! Q3 was all about AI. Here's the list of features and enhancements that have gone live, along with a list of what we have in pipeline for the last quarter: AI-powered agreement management Sending documents and authenticating recipients
    • Zoho sites header

      Good day, Im stuck with this situation. I choose a template for my website creation. I have tweaked every instance of the visual editor, regarding the header, I have created created customize fonts presets... I have followed every single step. and my
    • Zoho Books Sandbox environment

      Hello. Is there a free sandbox environment for the developers using Zoho Books API? I am working on the Zoho Books add-on and currently not ready to buy a premium service - maybe later when my add-on will start to bring money. Right now I just need a
    • Quick Create needs Client Script support

      As per the title. We need client scripts to apply at a Quick Create level. We enforce logic on the form to ensure data quality, automate field values, etc. However, all this is lost when a user attempts a "Quick Create". It is disappointing because, from
    • 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
    • DNS set up

      I want to create an email with my company domain. When I tried to add new record with cloudflare it didn't work. The DNS record can't be manually added. I followed the instruction but still can't add it. Could you help?
    • Pocket from Mozilla is closing shop. Don’t lose your favorites . Move them to Zoho Mail Bookmarks now! 📥🔖

      The end of Pocket shouldn't mean the end of your important links and content. Easily import them into Zoho Mail's Bookmarks and continue right where you left off. You can bring over your entire Saves, Collections, and tags just the way they are. Bookmarks
    • General suggestions

      Hello, I've picked this forum as it is at the top of the list! :) First suggestion: A general forum for issues and comments that are not specific to a particular Zoho application. Second suggestion: Put a link on the home page to "Zoho Identity Access Manager" The first suggestion came about because I didn't know where to post the second! ;) Regards Mark
    • All new Address Field in Zoho CRM: maintain structured and accurate address inputs

      The address field will be available exclusively for IN DC users. We'll keep you updated on the DC-specific rollout soon. It's currently available for all new sign-ups and for existing Zoho CRM orgs which are in the Professional edition. Managing addresses
    • Can't upload attachments.

      I can't upload attachment in Zoho Mail.
    • Need Guidance on SPF Flattening for Zoho Mail Configuration

      Hi everyone, I'm hoping to get some advice on optimizing my SPF record for a Zoho Mail setup. I use Zoho Mail along with several other Zoho services, and as a result, my current SPF record has grown to include multiple include mechanisms. My Cloudflare
    • How use

      Good morning sir I tried Zoho Mail
    • Next Page