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

                                  • Access Denied

                                    I am iOS Developer and updating our clients project and shifted ZohoDeskPortalCore SDKs from cocoapods to SPM and changed few lines of code but now i am get access denied, the help center app is unavailable. please contact administrator.
                                  • Using Zoho Desk to support ISMS process

                                    Hi, I am evaluating using Zoho Desk for security incident management. This seems to be aligned with Zoho Desk purpose as its just another type of incident. However in security incident management, ideally I can link incidents (tickets) with a risk from
                                  • Bin Locations

                                    Dear all, I am wondering if someone has the ability to develop the bin locations option for zoho inventory (integrated with zoho books) Regards, Ryan
                                  • TaxJar vs Avalara

                                    Hi, I'm evaluating adoption of a sales-tax service for US based business. Anyone else have experience with TaxJar and Zoho Books? I am a Zoho One subscriber so anticipate needing to use Flow to make this work. It seems like Avalara are simply too expensive
                                  • How to check Leads with no Task (open activity)

                                    Hi everyone, I was wondering if there’s a way to view leads that don’t have any tasks assigned or open activities linked to them.
                                  • What can we do on our end to improve the Answer bot answers?

                                    Hi, I'm using the Answer bot card in the Codeless bot builder. I've input several questions and their answers in the FAQ section to feed the Answer bot. The text is all in French, as this is the language our customers communicate in. I've tried testing
                                  • Taxes for EU B2B Transactions

                                    Currently, ZC doesn't seem to have a procedure for validating VAT numbers of businesses purchasing in another EU state, and removing local VAT is valid.  This is essential for all inter EU B2B trade.
                                  • How to upload file to Connect using API?

                                    Hi there. I looked at the API documentation and nowhere did it mention how to use the API method to upload a file even though it is mentioned that it is possible to be done so. Please help.
                                  • Group Tax in Service Line Items

                                    Hi FSM Team! I noticed that when you update a tax in the service line item the group tax is not showing up as an option. Let me know what can be done thank you!
                                  • FSM Improvement Idea - Show an Import button when there is no data

                                    I am setting up FSM for a client and I noticed that there is no option to import data, see screenshot below. Even when you click Create Contact there is only an option to Import from Zoho Invoice. It is only after you add at lease 1 record that the Import
                                  • Zoho FSM API Delete Record

                                    Hi FSM Team, It would be great if you could delete a record via API. Thank you,
                                  • OAUTH_SCOPE_MISMATCH Error for Marketing Automation APIs with CRM Plus Account

                                    I'm trying to integrate Marketing Automation journey triggering via API but getting OAUTH_SCOPE_MISMATCH errors. I need clarification on API access for CRM Plus users.
                                  • Access token generate from the refresh token not working for API

                                    Dear Sir/Madam, When I use my refresh token to obtain new access_token, that token return INVALID_TOKEN when the same API is called. I made sure that my api site is correct and match the auth web site. However the original access_token work fine.
                                  • Function #4: Schedule Customer Statements

                                    Regularly sending statements to customers is an imperative part of many business processes as it helps foster strong customer relationships and provides timely guidance on payments. While you can generate the statement of accounts and have it sent over
                                  • Limiting search or dependencies with an asterisk "*".

                                    I have a form with several dependency fields with options still developing for each field. Since these options were developing and not yet ready to be a selection in the field, I placed a filter for the dropdown field. In this filter, I selected fields
                                  • Cross Data Center Support for 1:1 Chats with External Users

                                    Hello Zoho Cliq Team, We hope you're doing well. We appreciate the recent enhancement that enables cross data center collaboration in external channels, which has already improved communication across distributed teams. However, we’ve noticed that this
                                  • Support Bots and Automations in External Channels

                                    Hello Zoho Cliq Team, How are you? We actively use Zoho Cliq for collaboration, including with our external developers. For this purpose, external channels are a key tool since they work seamlessly within the same interface as all of our other channels
                                  • Answer Bot and Personalized Questions

                                    Hi there, I have the same problem using the SalesIQ Answer Bot and the Zoho Desk Answer Bot (which really need different names, to be honest, in order to avoid confusion...) Customers that visit our website ask questions in the form of "What do you do?"
                                  • Handling Greetings/Small Talk at the Beginning of a Zobot Conversation

                                    Hello everyone, I’m currently configuring a **Zobot** in Zoho SalesIQ and everything is working as expected, except for one specific scenario at the very beginning of the conversation. My target audience has the habit of starting with a **greeting or
                                  • Regex in Zoho Mail custom filters is not supported - but it works!

                                    I recently asked Zoho for help using regex in Zoho Mail custom filters and was told it was NOT supported. This was surprising (and frustrating) as regex in Zoho Mail certainly works, although it does have some quirks* To encourage others, here are 3 regex
                                  • Importing a new list into campaigns

                                    I'm in the middle of switching my email platform to campaigns. I have a list that I want to import, and it overlaps with my existing Zoho CRM list. The fields in my Zoho CTM are more robust. Will this new list that I upload into my campaigns overwrite
                                  • when I email a invoice how can i see it was sent and also were i can go to see all emails sent

                                    when I email a invoice how can i see it was sent and also were i can go to see all emails sent?
                                  • Showing description in timesheet and timelogs.

                                    I am wondering if it’s possible in version 5 of Zoho People to have the description show by default or with a manipulation on the user’s part. Let me show you what I mean. As you can see this is the view for the users. Now if they want to see the full
                                  • How can I see content of system generated mails from zBooks?

                                    System generated mails for offers or invices appear in the mail tab of the designated customer. How can I view the content? It also doesn't appear in zMail sent folder.
                                  • CRM Blueprint Notification by Cliq

                                    Dear Zoho team, In Workflow, there is nofication by cliq, but in blueprint, there is no option as cliq notification. I think it is very convenient to get notified by Cliq , as there are multi modules in apps, but we will always check Cliqs
                                  • Zoho People Attendance Regularization – Wrong Total Hours Displayed

                                    While using Zoho People, I observed that the attendance regularization is showing wrong total hours when applied to past dates. For example, if a check-in is added at 10:00 AM and check-out at 6:00 PM for a previous date, the system sometimes calculates
                                  • Sync Contacts in iOS

                                    What does the "Sync Contacts" feature in the iOS Zoho Mail app do?
                                  • Live webinar: Craft the ideal sales pitch deck with Show

                                    Every great sale starts with a great story. And your pitch deck? That’s where the story takes shape. But too often, these presentations end up looking generic, overloaded with text, or lacking structure. The good news is, it's easier to fix than you think!
                                  • Project Statuses

                                    Hi All, We have projects that sometimes may not make it through to completion. As such, they were being marked as "Cancelled". I noticed that these projects still show as "Active" though which seems counter intuitive. In fact, the only way I can get them
                                  • 👋 Welcome to the Zoho MCP Community

                                    Hello all, glad to have you here! This is your space for everything AI agents, MCP tools, and intelligent business apps. This community is for you — developers, partners, creators, and businesses exploring how agents can transform work. Whether you’re
                                  • Suitability of Zoho One (Single User License) for Multi-State GST Compliance & Cost Analysis

                                    Hello Zoho Team, I am an e-commerce business owner selling on platforms like Amazon, Flipkart, and Meesho, and I'm currently using their fulfillment warehouses. I have two GSTIN registrations and am planning to register for an additional 2-3 to expand
                                  • DNS Manager

                                    Where Can I find my DNS manager so I can link this to click funnels or AWEBER
                                  • Forwarder

                                    Hi, I tried to add a forwarder from which emails are sent to my main zoho account email . However, it asks me for a code that should be received at the forwarder email, which is still not activated to send to my zoho emial account. So how can I get the
                                  • Forwarder

                                    Hi, I tried to add a forwarder from which emails are sent to my main zoho account email . However, it asks me for a code that should be received at the forwarder email, which is still not activated to send to my zoho emial account. So how can I get the
                                  • How do I sync multiple Google calendars?

                                    I'm brand new to Zoho and I figured out how to sync my business Google calendar but I would also like to sync my personal Google calendar. How can I do this so that, at the very least, when I have personal engagements like doctor's appointments, I can
                                  • Need to extract date from datetime field

                                    I have a datetime field and need only the date part from it. I am unable to find a built-in function that would be <DateTime>.Date(). I don't think I want to go the string conversion route of converting the datetime to string and then parsing out values and create a date out of it. Any one out there has a better solution to this? Thanks in adavnce. Regards Moiz Tankiwala Smart Training & IT Solutions
                                  • How to Hide Article Links in SalesIQ Answer Bot Responses

                                    I have published an article in SalesIQ, and the Answer Bot is fetching the data and responding correctly. However, it is also displaying the article link, which I don’t want. How can I remove the link so that only the message is shown?
                                  • New in Cadences: WhatsApp follow-ups, upgraded limits, and options for add-ons

                                    Hello everyone, We're rolling out two key updates to help you engage better and scale smarter with Cadences in Zoho CRM. Reach customers on WhatsApp, directly from Cadences Previously, Cadences have enabled you to automate follow-ups through emails, calls,
                                  • additional accounts

                                    If I brought 5 emails to my account. Can I later buy additional emails.
                                  • Issue in Zoho People Regularization – Incorrect Hour Calculation

                                    I have noticed that when applying attendance regularization in Zoho People for previous dates, the total working hours are not calculated correctly. For example, even if the check-in is 10:00 AM and check-out is 6:00 PM, the system shows an incorrect
                                  • Next Page