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!





      Zoho Campaigns Resources


        • Desk Community Learning Series


        • Digest


        • Functions


        • Meetups


        • Kbase


        • Resources


        • Glossary


        • Desk Marketplace


        • MVP Corner


        • Word of the Day


        • Ask the Experts


          Zoho CRM Plus Resources

            Zoho Books Resources


              Zoho Subscriptions Resources

                Zoho Projects Resources


                  Zoho Sprints Resources


                    Zoho Orchestly Resources


                      Zoho Creator Resources


                        Zoho WorkDrive Resources



                          Zoho CRM Resources

                          • CRM Community Learning Series

                            CRM Community Learning Series


                          • Tips

                            Tips

                          • Functions

                            Functions

                          • Meetups

                            Meetups

                          • Kbase

                            Kbase

                          • Resources

                            Resources

                          • Digest

                            Digest

                          • CRM Marketplace

                            CRM Marketplace

                          • MVP Corner

                            MVP Corner




                            Zoho Writer Writer

                            Get Started. Write Away!

                            Writer is a powerful online word processor, designed for collaborative work.

                              Zoho CRM コンテンツ




                                ご検討中の方

                                  • Recent Topics

                                  • Having Trouble Opening The Candidate Portal

                                    Recently am having trouble opening the Candidate Portal. It keeps loading but cannot display any widgets. Tried Safari, Chrome and Edge. Non of them work. Please solve the problem ASAP.
                                  • Checkboxes not adhering to any policy in mail merge - data from CRM

                                    I want checkboxes to appear depending on whether the checkbox in the CRM module is ticked or not. However, the tickboxes that appear are either ticked or not, but don't correlate to the actual selections in the CRM module. This is is despite updating
                                  • Items Landed Cost and Profit?

                                    Hello, we recently went live with Zoho Inventory, and I have a question about the Landed Cost feature. The FAQ reads: "Tracking the landed cost helps determine the overall cost incurred in procuring the product. This, in turn, helps you to decide the
                                  • Show elapsed time on the thank-you page?

                                    Is it possible to display the total time a user spent filling out a Zoho Form on the thank-you? I’d like to show the difference between the `form submission timestamp` and the `start time` (currently have a hidden Date-Time field set to autofill the date
                                  • CC and/or BCC users in email templates

                                    I would like the ability to automatically assign a CC and BCC "User (company employee)" into email templates. Specifically, I would like to be able to add the "User who owns the client" as a CC automatically on any interview scheduled or candidate submitted
                                  • 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
                                  • Create Contract API Endpoint Unclear "inputfields" Requirements

                                    Hello, I'm trying to create a Deluge function that accepts inputs from a form in Zoho Creator and creates a barebones contract of a given type. See below for the current code, cleaned of authentication information. // Fetch form data // Hidden field client_name
                                  • 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
                                  • Kaizen #46 - Handling Notes through Zoho CRM API (Part 1/2)

                                    Hello everyone! Welcome back to another week of Kaizen! This week, we will discuss Handling Notes through Zoho CRM API. What will you learn from this post? Notes in Zoho CRM Working with Notes through Notes APIs 1. Notes in Zoho CRM 1a. Why add Notes to records? Notes are a great way to summarize your observations on customer and prospect interactions and outcomes. By saving notes as CRM data, a sales rep will always be able to keep track of how a sale is progressing. To know more about notes in
                                  • Marketer's Space - Why email marketing matters in ecommerce (and how to get started with Zoho Campaigns)

                                    Hello Marketers, Welcome to this week's Marketer's space post. Today, we'll discus why email marketing matters in ecommerce businesses. Running an online store is exciting but challenging. If you're running an online store, you've probably experienced
                                  • Zoho Campaigns Event timestamps do not propagate to Zoho CRM

                                    We have integrated Zoho CRM and Zoho Campaigns. But when looking at Contact records, the Campaign event data is missing the actual timestamps: especially when a particular email was sent. They're not in the Campaigns related list, and the cannot be found
                                  • Kaizen #121 : Customize List Views using Client Script

                                    Hello everyone! Welcome back to another interesting Kaizen post. In this post, we can discuss how to customize List Views using Client Script. This post will answer the questions Ability to remove public views by the super admin in the Zoho CRM and Is
                                  • Setting default From address when replying to request

                                    At the moment, if I want to reply to a request, the From field has three options, company@zohosupport.com, support@company.zohosupport.com, and support@company.com.  The first two are really internal address that should never be seen by the customer and
                                  • In place field editing for candidates

                                    Wondering about any insight/best practices for efficiently updating candidate records while reviewing them in a Job Opening pipeline. We can do in-field editing (e.g. update job title or City) only when we have the full candidate record open, however
                                  • Explore Your Support Reach with Zoho Assist’s Geo Insights

                                    Understanding where your remote support sessions are happening can help you make smarter decisions, allocate resources effectively, and improve overall customer satisfaction. In this week's Zoho Assist's community post we will be exploring Geo Insights
                                  • Error when sending emails from Zoho

                                    Hello, When trying to send an email from Zoho CRM I keep getting the below error: javax.mail.AuthenticationFailedException: 535 5.7.139 Authentication unsuccessful, the user credentials were incorrect. Any support on this will be much appreciated. Thanks,
                                  • Direct Integration Between Zoho Cliq Meetings and Google Calendar

                                    Dear Zoho Team, We’d like to submit the following feature request based on our current use case and the challenges we’re facing: 🎯 Feature Request: Enable meetings scheduled in Zoho Cliq to be automatically added to the host's Google Calendar, not just
                                  • Formatting of text pasted into Zoho documents

                                    Howdy, I'm a newbie and finding Zoho an improvement to MS Word. Consider yourself hugged. High on my wish list would be plain text cut-and-paste. When pasting text from the web to Zoho, presently Zoho imports the formatting along with the text. This means that every cut-and-paste operation brings in text in a different font, size, or style. Can we have at least the option of importing plain text without formatting (or better yet, is this option already out there?) ... Thanks Helen
                                  • Add additional features to Zoho Tables

                                    Zoho Tables is a really great tool, why not add features like diagramming capability into the tool from applications like Draw.io which I believe is open source, you should be able to do wireframes, process flow diagrams, network design, etc. Please note
                                  • Zoho sheet

                                    Unable to share zoho sheet with anyone on internet with editer option only view option is show
                                  • The Social Wall: August 2025

                                    Hello everyone, As summer ends, Zoho Social is gearing up for some exciting, bigger updates lined up for the months ahead. While those are in the works, we rolled out a few handy feature updates in August to keep your social media management running smoothly.
                                  • The Social Wall: July 2025

                                    Hello everyone! July has brought some exciting new updates to Zoho Social. From powerful enhancements in the Social Toolkit to new capabilities in the mobile app, we’ve packed this month with features designed to help you level up your social media presence.
                                  • Use Zoho Creator as a source for merge templates in Zoho Writer

                                    Hello all! We're excited to share that we've enhanced Zoho Creator's integration with Zoho Writer to make this combination even more powerful. You can now use Zoho Creator as a data source for mail merge templates in Zoho Writer. Making more data from
                                  • Tagged problem !!!

                                    Damn it, we're one of dozens of construction companies in Africa, but we can't link purchasing invoices to projects. Why isn't this feature available?
                                  • Enable Password Import option in ulaa browser

                                    Dear Ulaa Team, I noticed that the Ulaa Password Manager currently offers an option to export passwords, but not to import them. This limitation poses a challenge for users like me who have stored numerous credentials in browsers like Chrome. Manually
                                  • Limited review (/questions) for Bookings 2.0

                                    Hi all, I'm writing this review of Bookings 2.0 for two reasons: 1) it may be of interest to others, and 2) I'd like to be corrected if I'm wrong on any points. It's a very limited review, i.e. the things that have stood out as relevant, and particularly
                                  • Syntax for URLs in HTML Snippets

                                    What are some best practices for inserting a URL in an HTML snippet? I've looked at Zoho Help articles on navigation-based and functional-based URLs, but I'm still unclear on how to incorporate them in an HTML snippet. For example, 1. How do I link to
                                  • The Social Wall: June 2025

                                    Hello everyone, We’re back with June Zoho Social highlights. This month brought some exciting feature updates—especially within the Social Toolkit—to enhance your social media presence. We engaged with several MSME companies through community meet-ups
                                  • Make panel configuration interface wider

                                    Hi there, The same way you changed the custom function editor's interface wider, it would be nice to be able to edit panels in pages using the full width of the screen rather than the currently max-width: 1368px. Is there a reason for having the configuration panel not taking the full width? Its impossible at this width to edit panels that have a lot of elements. Please change it to 100% so we can better edit the layouts. Thanks! B.
                                  • Tip 7: How to fetch data from another application?

                                    Hi everyone, Following our Zoho Creator - Tips and Tricks series every fortnight, we are back today with a tip based on one of the most popular questions asked in our forum. This tip would help you fetch data from another application(App B) and use it
                                  • The Social Wall: May 2025

                                    Hey everyone, We're excited to share some powerful updates for the month of May! Let's take a look! Reply to your Instagram and Facebook comments privately through direct messages Are you tired of cluttered comment threads or exposing customer queries
                                  • Sub-Form Fields as Filters for Reports

                                    Hi, I would like to use the Sub-Form Fields as Filters in Reports just like we do for Main Page Fields. Thanks Dan
                                  • How to change the format for phone numbers?

                                    Mobile phone numbers are currently formatted (###) ###-####.  How can I change this to a more appropriate forms for Australia being either #### ### ### or (#)### ### ###?
                                  • Zoho CRM Formula - Current Time minus Date/Time field

                                    Hello, I am trying to prevent duplicate emails going to clients when more than 1 deal is being updated. To do this, I would like to create a formula to identify if a date/time field is >= 2 hours ago. Can someone please help me write this formula? Example:
                                  • Per Level Approval for admins

                                    We need Process admins like Zoho CRM in Zoho Books for per stage approval Currently in books, admins only have the option for Final Approval But for example, in cases like when an employee is on leave, we can't just approval one level we only have option
                                  • Default Sorting on Related Lists

                                    Is it possible to set the default sorting options on the related lists. For example on the Contact Details view I have related lists for activities, emails, products cases, notes etc... currently: Activities 'created date' newest first Emails - 'created
                                  • Billing Management: #7 Usage Billing in Telecom & Internet Service Provider

                                    Telecom and Internet Service Providers operate in markets where usage varies drastically from one customer to another. While flexible, usage-based models align revenue directly with consumption, they also introduce operational challenges like real-time
                                  • Zoho Sprints - Q3 updates for 2025

                                    The updates for the third quarter of 2025 are out. A few significant features and enhancements have been rolled out to improve user experience and product capabilities. The following are the updates: Manage tags and cluster tags Record and maintain project
                                  • Kaizen #208 - Answering your Questions | Functions, AI and Extensions

                                    Hello Developers! Welcome back to a fresh week of Kaizen! We are grateful for your active participation in sharing feedback and queries for our 200th milestone. This week, we will answer the queries related to Functions and Extensions in Zoho CRM. 1.
                                  • Zoho Projects Webhook fails with HTTP Error 0

                                    Hello Zoho Community, I am pulling my hair out over this one. I have setup a very basic http(s) server that always responds "ok" and code 200 to incoming GET requests. It will accept any parameters, and any path. Really, all it does is say "ok," and log
                                  • Next Page