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

    • Create online meetings for Booking Pages with Zoho Meetings and Zoom

      Greetings, We hope you're all doing well. We're excited to share some recent enhancements to Bigin's Booking Pages. As you know, Booking Pages let you create public pages to share your availability so that your customers can easily book time slots with
    • Filters in audit logs

      Greetings, I hope all of you are doing well. We're happy to announce a few recent enhancements we've made to Bigin. We'll go over each one in detail. Previously, there were no filters available to narrow down data in audit logs. Now, we've introduced
    • Enhanced help options in Bigin

      Greetings, We're excited to introduce a new enhancement to Bigin's Help section: a comprehensive Help Options panel that brings together all your support resources in a single, well-organized space. Previously, the Need Help? menu provided only a limited
    • Zoho FSM API Developer Needed

      Hi, I’m looking for a developer with experience using Zoho FSM APIs. Scope: Connect WordPress website booking form to Zoho FSM Check availability (date, time, region) Create Work Orders + Service Appointments automatically Notify both customer and scheduler
    • Revenue Management: #4 What if there are uncertainties in project or service delivery?

      Our previous post taught us how Zoho Billing makes life easy for businesses with its automated revenue recognition rule. However, certain businesses have more challenges that an automated system cannot handle, and there are certain situations where automated
    • This mobile number has been marked spam. Please contact support-as@zohocorp.com

      Bom dia, estou tentando colocar o número 11 94287-6695 e esta com erro "This mobile number has been marked spam. Please contact support-as@zohocorp.com" pode me ajudar, por favor?
    • Items Serial Tracking Issue

      We enabled Zoho Items inventory tracking then disabled it after some time now we want to enable it again When I check the missing serial number reports I see one item But I cant see any option to Add the serial numbers Where and how to add the serial
    • Composite Services and Account Tracking

      I am looking to garner support/request the ability to make composite services. A quick search in the forums brings up multiple requests for this feature. I fail to see why an item is mandatory while services are optional. I also would like to see the
    • Zoho Payroll integration with Zoho Books - unable to match multiple bank feeds to one wage payment

      For one employee's wage, I make two partial payments. Those bank feed transactions come into Zoho Books via bank integration. I make one pay-run for the month in Zoho Payroll and that comes into Zoho Books via the Zoho integration. Zoho Books doesn't let me match multiple bank feed transactions against a single wage item. Please fix urgently. I can't complete my books because of this.
    • Add Checkbox Selection & Bulk Actions to Delivery Challans Module

      Hi Zoho Team, I’ve noticed that in the Sales Orders module, there are checkboxes beside each entry that allow users to select multiple records for bulk actions such as print, email, or delete. However, in the Delivery Challans module, this option appears
    • Can't be able to check-in in laptop

      even after giving location access still i can't be able to check-in in laptop.
    • Compensation Cess on Coal ₹400 per tonne. ?????

      The compensation cess rate varies by the type of product. And the cess is calculated based on the value of the product without GST. Coal, for example, comes with a cess of ₹400 per tonne. That means that if you sell 2 tonnes of coal that have a value
    • 7 month over zoho book purchase but still not immpliments Golive

      7 month over zoho book purchase but still not immpliments Golive one problems zoho team short out then other problems come still very poor mangments and immliments team . struggling with the templates in ZOHO Books. Especially with the placement of some
    • Average Costing / Weighted Average Costing

      Hello fellow maadirs. I understand Zoho Books uses FIFO method of dealing with inventory costing, but do you guys have any plans to introduce average costing? We indians need average costing. It's part of our culture. Please. I beg thee. Thanks.
    • SMS to customers from within Bigin

      Hi All, Is there anyone else crying out for Bigin SMS capability to send an SMS to customers directly from the Bigin interface? We have inbuilt telephony already with call recordings which works well. What's lacking is the ability to send and receive
    • How to update/remove file in zoho creator widgets using javascript API

      Hi Team, I have developed a widget which allows inserting and updating records I have file upload field with multiple file upload. Now while doing insert form record, I am using uploadFile API to upload files for that record. I am using updateRecord API
    • Parent & Member Accounts (batch updating / inheritance)

      Hello, I find the Parent Account functionality very useful for creating custom views and reports, but was wondering if I can also carry out batch editing on all members (aka children) of a Parent Account at the same time. Alternatively, can I set members to automatically inherit the values of the parent? For example: We have a chain of supermarkets that buy our products. These supermarkets are all members of a Parent Account in our CRM. We release a new product and all of the member stores wish to
    • Edit Legend of Chart

      I would like to edit the legend of the chart. Every time I enable the legend, I get a very unhelpful (1), and when I try to type to change to what I would desire, nothing happens, which is very frustrating. I've gone through your online tutorials and nowhere can I find a legend settings button. This seems a simple fix, where can edit the legend? Thanks.
    • Extended timeouts for APIs beyond 40secs for to accomodate LLMs

      A 40 second max response time for API calls is fine when connecting to most services, however is unsuitable when dealing with LLMs (ChatGPT/Claude/Gemini) where the response timing is very uncertain. Is there any way to increase this? It would be great
    • Deletion of Zoho Account

      To whom it may concern, Good day, My account has been created incorrectly in Zoho and I am not able to join my Company's Zoho account - attached screenshot for your kind reference Alphatronmarine - Portal Kindly advise procedure to delete this current
    • Workflow for deposit to bank account

      Hello, Is it possible to make a workflow when a deposit is made to your bank account which is coupled to Zoho books? I want Zoho to sent an email each time a deposit is made to our bank account via a workflow. Regards, Steven
    • Marking Retainer invoice paid through Deluge

      Hey Everyone, We have a scenario where we are collecting deposit payments on our website. Now, in zoho books, we need to create a retainer invoice and mark it as paid automatically using deluge just like we can mark normal invoices as paid. I have tried
    • Create a new record in custom module vi custom button

      I have zoho books premium plan . I have 2 custom modules in zoho books. 1. Goods Receipt 2. Delivery Order, I need to select multiple records from Goods Receipt and create a new Delivery order from these multiple records. (like multilple sales order into
    • Profile date settings

      At present I have "EEE, MMMM dd, yyyy" but this takes an exessive amount of column space, we should be able to input our own format. I would like to use "EEE, MMM dd, yy" - a much shorter version of the above but with the same abbreviated info, requiring
    • Delivery Method Field in Sales Order Module

      In Books and in Sales orders, the "Delivery Method" field seems to allow for anything to be entered and it seems to store those entries for future use.  When you chose to convert a sales order to a purchase order, the related field is now called "Shipment
    • Editing / Removing stages for pipeline

      Hello, I'm trying to create a new pipeline. I created a new stage and made an error when entering the probability. How can I edit fields in stages that I created? Can I delete these stages from "Add Stages" list?
    • Dynamically Filter User Lookup in CRM Subform

      We have a subform called Pricing Calculator in the Zoho CRM Opportunity module and need some assistance. Current Setup: First column: Picklist (Level) Second column: User Lookup field When a Level is selected, we want the User lookup to display only users
    • change time zone

      can't seem to figure out how to change the time zone of the project
    • Bigin iOS app update: Built-in telephony and RingCentral support

      Hello everyone! We are excited to introduce Built-In Telephony and RingCentral support in the latest iOS version(v1.11.13) of the Bigin mobile app. Once the integration is completed on the Bigin desktop site(bigin.zoho.com), you can choose the Built-In
    • Add Image or Update Image API - for Items Module

      I am trying to add new Items to Zoho Inventory from Zoho Creator. I achieved this using Zoho Inventory Create Item API, but how to add or update the item image from Zoho Creator to Zoho Inventory Item Module?
    • Introducing Booking Pages—a topping for your Calendar Scheduling needs!

      Greetings, We're here with a new topping for Bigin! Let's dive into the details. What does this topping do? Scheduling appointments with customers is one of the most common challenges small businesses face on a daily basis, as it often involves frequent
    • Debugging `try` blocks : Tip

      I find it annoying that if one line inside a `try` block has an error, the Deluge arser points the beginning of the block to the location of the error. BUT, if you temporarily comment out the initial `try {`  The parser goes through the whole block and
    • [Product Update] TimeSheets module is now renamed as Time Logs in Zoho Projects.

      Dear Zoho Analytics customers, As part of the ongoing enhancements in Zoho Projects, the Timesheets module has been renamed to Time Logs. However, the module name will continue to be displayed as Timesheets in Zoho Analytics until the relevant APIs are
    • Use approval workflow comments in record scripts

      Greetings, i'm running an approval workflow for my records, during approval/rejection there is a step where comments are entered. i want to add there comments to the record and to use them in various deluge scripts like sending emails and so on.  how
    • ZOHO Store

      Not able to make a payment We are using Zoho One, and we are from India. The payment currency, which shows for us, is in USD. But the system says we can choose Country/Region India if it shows INR only. Attaching screenshots for more info.
    • Support Migration into Aliases in Zoho Mail

      Hello Zoho Mail Team, How are you? We are in the process of migrating some of our users from Google Workspace (Gmail and Google Drive) to Zoho. During this process, we noticed that Zoho Mail currently only supports migration into a primary mailbox and
    • API for Z Workdrive Flow Make-Integromat ?

      We are zoho workdrive fans Also we would like to have an api to work with Zoho Flow or with Make better known by its old name INTEGROMAT Is it planned and when? 3 months -6 months or more?
    • Apps Pane no longer visible

      I have read all the info and help and nothing works, I do not have a "show apps" anywhere and I can no longer see my Apps pane in the left hand side of mail, please advise how to get this back
    • Canvas View - Print

      What is the best way to accomplish a print to PDF of the canvas view?
    • 5名限定 課題解決型ワークショップイベント Zoho ワークアウト開催のお知らせ(8/21)

      ユーザーの皆さま、こんにちは。Zoho ユーザーコミュニティチームの藤澤です。 8月開催のZoho ワークアウトについてお知らせします。 今回はZoomにてオンライン開催します。 ▷▷参加登録はこちら:https://us02web.zoom.us/meeting/register/eVOEnBsSQ2uvX4WN5Z5DeQ ━━━━━━━━━━━━━━━━━━━━━━━━ Zoho ワークアウトとは? Zoho ユーザー同士で交流しながら、サービスに関する疑問や不明点の解消を目的とした「Zoho
    • Next Page