Kaizen #181 - Mandating Subform Data for Blueprint Transitions using Widget

Kaizen #181 - Mandating Subform Data for Blueprint Transitions using Widget



Hello Developers!

Welcome back to another week of Kaizen! 

This time, we are tackling a common challenge on how to enforce subform data from a different module before allowing a blueprint transition in Zoho CRM Deals module.

Many CRM workflows require checking and collecting related records' data across modules before advancing a deal, case, or order to the next stage. Zoho CRM Blueprint natively support subforms from Quotes, Sales Orders, and Invoices for the Deals module with the help of Associated Items in the transition settings. 

Let us explore how to mandate custom subforms' data from a different module for a blueprint transition.

Why Mandate Subform Data from a Different Module?

In Zoho CRM, subforms manage multiple data entries under a single parent record. However, certain blueprint transitions may depend on subform data from related modules, such as:  
  • A Deal's transition may depend on the document data stored in the associated Contact’s subform.
  • A Service Request requiring validation against a subform in the related Account before processing.  
  • A Loan Application requiring income proof from the Customer’s subform before approval.  
Since blueprint transition rules only validate fields within the same module, you can use a custom widget to check and update subform data across modules before proceeding.

Business Scenario: Insurance Deals Qualification

Consider Zylker, an insurance company, using Zoho CRM to manage customers and streamline processes. Their sales process follows this blueprint when a deal reaches the Qualification stage:
Insurance Sales Blueprint

Steps to Build a Blueprint Widget

Step 1 - Review Basics

Refer to our earlier Kaizen on CLI Installation, Creating a Widget Project, and Internal hosting of the same.

Step 2 - Develop your Widget

After setting up the widget project using CLI, implement the logic based on your business case.

Here’s the logic for the sample use case we are discussing:

Widget Execution During Transition
  • When the user clicks the Collect Requirements transition, the widget loads.
  • Using the PageLoad event listener, retrieve the current record's ID and module name.
  • Use the GET Records API via its JS SDK to fetch the Contact ID linked to the Deal. 
ZOHO.embeddedApp.on("PageLoad", function(data) {
      // Fetch the current page's record details
      const recordId = data.EntityId;
      const moduleName = data.Entity;
      ZOHO.CRM.API.getRecord({Entity: moduleName, RecordID: recordId})
        .then(function(response) {
          const record = response.data[0];
          console.log("Current Record Details:", record);
          // Fetch the associated contact ID
 contactId = record.Contact_Name.id;

Check and Collect Required Document Details
  • Using the Contact ID, run a COQL query using Connection JS SDK to check if each Document Category has at least one entry in the Document Details subform.
Notes
Notes
In invoke connection JS SDK, use param type 2 for the API request payload inside the parameter key and param type 1 for regular parameters.

Explore the Working with Connections help page and create a connection with the necessary scopes to invoke the COQL API.
  • If all four categories (Address Proof, ID Proof, Income Proof, Medical Report) have at least one entry, the widget allows the transition immediately.
  • If any category is missing, the widget prompts the user to enter the details in a table that mirrors the Document Details subform in the Contacts module.
// Make a query API call 
          const query = {
            "select_query": `select Document_Category,COUNT(id) from Document_Details where id is not null and Parent_Id='${contactId}' group by Document_Category`
          };
          ZOHO.CRM.CONNECTION.invoke("crm_oauth_connection", {
            method: "POST",
            url: "https://www.zohoapis.com/crm/v7/coql",
            parameters: query,
            param_type: 2,
            headers: {
              "Content-Type": "application/json"
            }
 }).then(function(response) {
     const data = response.details.statusMessage.data;
            if (response.details.statusMessage === "" || (data && data.length < 4)) {
              createSubformUI();
              document.getElementById('contentContainer').style.display = 'block';
            } else if (data && data.length === 4) {
              document.getElementById('messageContainer').style.display = 'block';
              // Enable the "Move to Next State" button if all files are already updated
              const nextStateButton = document.querySelector('.nextStateButton');
              nextStateButton.disabled = false;
              nextStateButton.style.backgroundColor = ''; 
            }
 })

Update the Contact's Subform
  • The user enters the document details and clicks the Save button in the widget. 
  • Since subform updates act like a PATCH request, any existing record IDs must be included in the update payload to retain them. To get the existing subform record IDs make a  GET Records API call via its JS SDK
async function getExisitingSubFormRecords(contactId) {
let exisitingRecords = [];
awaitasync function getExisitingSubFormRecords(contactId) {
let exisitingRecords = [];
await ZOHO.CRM.API.getRecord({ Entity: "Contacts", RecordID: contactId })
.then(function (response) {
const record = response.data[0];
console.log("Current Record Details:", record);

if (record.Document_Details)
{
record.Document_Details.forEach(function (document) {
exisitingRecords.push({id: document.id});
});
}
})
.catch(function (error) {
console.error("Error fetching records:", error);
});
return exisitingRecords;
} ZOHO.CRM.API.getRecord({ Entity: "Contacts", RecordID: contactId })
.then(function (response) {
const record = response.data[0];
console.log("Current Record Details:", record);
record.Document_Details.forEach(function (document) {
exisitingRecords.push({id: document.id});
});
})
.catch(function (error) {
console.error("Error fetching records:", error);
});
return exisitingRecords;
}
  • Clicking the Save button executes the following actions:
    -> Uploads the selected file to Zoho File System (ZFS) using the Upload File API through its JS SDK.
    -> Updates the Document Details subform in the associated Contact record by adding the file ID from the upload response and each row's entry using the Update Records API (via the Update Record JS SDK).
  • Once the subform is successfully updated, the widget allows the transition to next Blueprint state.
async function updateRecord(event) {
event.preventDefault();
// Collect user entries from each row
const rows = document.querySelectorAll('#documentsTable tbody tr');
const documentDetails = await Promise.all(Array.from(rows).map(async (row, index) => {
const documentCategory = row.querySelector('select[name="documentCategory"]').value;
const documentNumber = row.querySelector('input[name="documentNumber"]').value;
const documentName = row.querySelector('input[name="documentName"]').value;
const documentFile = row.querySelector('input[name="upload"]').files[0];
const fileId = await uploadFile(documentFile);
return {
Document_Category: documentCategory,
Document_Number: documentNumber,
Document_Name: documentName,
Upload: [
{
file_id: fileId
}
]
};
}));
// Get the existing subform records
const existingRecords = await getExisitingSubFormRecords(contactId);
// Merge the existing records with the new records
existingRecords.forEach(record => documentDetails.push(record));
// Prepare the payload for the update API call
const payload = {
id: contactId,
Document_Details: documentDetails
};
// Make the update API call
ZOHO.CRM.API.updateRecord({
Entity: "Contacts",
APIData: payload
}).then(function (updateResponse) {
console.log("Update response:", updateResponse);
const saveButton = document.querySelector('.saveButton');
saveButton.textContent = "Saved";
saveButton.disabled = false;
saveButton.style.backgroundColor = 'grey';
// Enable the "Move to Next State" button after saving
const nextStateButton = document.querySelector('.nextStateButton');
nextStateButton.disabled = false;
nextStateButton.style.backgroundColor = ''; 
})

Step 3 - Validate and Pack the Widget

  • Follow the steps given in the Widget help page to validate and package the widget.
  • Go to Zoho CRM > Setup > Developer Hub > Widgets and click Create New Widget.
  • Fill in the required details as shown in this image and ensure to select Blueprint as the widget type.
    Creating a Blueprint Widget

Step 4 - Associate the Widget with the Blueprint

  • Navigate to Setup > Process Management > Blueprint and open the Deals Blueprint created for this use case.
  • Click on the Collect Requirements transition.
    Associate Widget to a Blueprint Transition
  • In the During tab on the left pane, select Widgets and associate the newly created widget.
  • Publish the Blueprint to activate the changes.

Try it Out! 

A complete working code sample of this widget is attached at the bottom of this post for reference. 
 
Now, let us see how this Blueprint works from the Deals page:  
  1. All required document details are available: The widget validates the Contact’s subform and allows the transition.  



  2. Missing or incomplete document details: The widget prompts the user to enter the missing details, updates the Contact’s subform, and then enables the transition.  



This approach ensures that required subform data from another module is validated and captured before proceeding with a Blueprint transition.  

Would you like us to address any of your pain-points or have a topic to discuss? Let us know in the comments or reach out to us via support@zohocrm.com.

Until next time, Happy Coding! 

---------------------------------------------------------------------------------------------------------------------------------------

Additional Reading

---------------------------------------------------------------------------------------------------------------------------------------


Info
More enhancements in the COQL API are now live in Zoho CRM API Version 7. Check out the V7 Changelog for detailed information on these updates.


      • Sticky Posts

      • Kaizen #197: Frequently Asked Questions on GraphQL APIs

        🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Kaizen #198: Using Client Script for Custom Validation in Blueprint

        Nearing 200th Kaizen Post – 1 More to the Big Two-Oh-Oh! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Celebrating 200 posts of Kaizen! Share your ideas for the milestone post

        Hello Developers, We launched the Kaizen series in 2019 to share helpful content to support your Zoho CRM development journey. Staying true to its spirit—Kaizen Series: Continuous Improvement for Developer Experience—we've shared everything from FAQs
      • Kaizen #193: Creating different fields in Zoho CRM through API

        🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Client Script | Update - Introducing Commands in Client Script!

        Have you ever wished you could trigger Client Script from contexts other than just the supported pages and events? Have you ever wanted to leverage the advantage of Client Script at your finger tip? Discover the power of Client Script - Commands! Commands

        • Recent Topics

        • Converting Sales Order to Invoice via API; Problem with decimal places tax

          We are having problems converting a Sales Order to an Invoice via API Call. The cause of the issue is, that the Tax value in a Sales Order is sometimes calculated with up to 16 decimal places (e.g. 0.8730000000000001). The max decimal places allowed in
        • Upload API

          I'm trying to use the Upload API to upload some images and attach them to comments (https://desk.zoho.com/DeskAPIDocument#Uploads#Uploads_Uploadfile) - however I can only ever get a 401 or bad request back. I'm using an OAuth token with the Desk.tickets.ALL
        • How to sync from Zoho Projects into an existing Sprint in Zoho Sprints?

          Hi I have managed to integrate Zoho Projects with Zoho Sprints and I can see that the integration works as a project was created in Zoho Sprints. But, what I would like to do is to sync into an existing Zoho Sprints project. Is there a way to make that
        • How to record company set up fees?

          Hi all, We are starting out our company in Australia and would appreciate any help with setting up Books accounts. We paid an accountant to do company registration, TFN, company constitution, etc. I heard these all can be recorded as Incorporation Costs, which is an intangible asset account, and amortised over 5 years. Is this the correct way to do it under the current Australian tax regulations? How and when exactly should I record the initial entry and each year's amortasation in Books? Generally
        • How to create a drop down menu in Zoho Sheets

          I am trying to find out, how do I create a drop down option in Zoho sheet. I tried Data--> Data Validation --> Criteria --> Text  --> Contains. But that is not working, is there any other way to do it.  Thanks in Advance.
        • Show Payment terms in Estimates

          Hi,  we are trying to set up that estimates automatically relates payment terms for the payment terms we introduced on Edit contact (Field Payment terms).  How can it be done? Our aim is to avoid problems on payment terms introduced and do not need to introduce it manually on each client (for the moment we are introducing this information on Terms and Conditions.  Kind Regards, 
        • Rich-text fields in Zoho CRM

          Hello everyone, We're thrilled to announce an important enhancement that will significantly enhance the readability and formatting capabilities of your information: rich text options for multi-line fields. With this update, you can now enjoy a more versatile
        • How can I calculate the physical stock available for sale?

          Hey Zoho Team,  I've tried to calculate the physical stock on hand in various ways - but always receive a mismatch between what's displayed in Zoho Inventory & analytics.  Can you please let me know how the physical stock available for sale is calculated?
        • When dispatched to crew, assigning lead missing

          Hello, For the past two or three weeks, whenever an officer assigns Service Appointment to a team, the lead person is missing from the assigned service list. Therefore, we have to reschedule the SA and then the lead person becomes visible in the assigned
        • Create Lead Button in Zoho CRM Dashboard

          Right now to create Leads in the CRM our team is going into the Lead module, selecting the "Create Lead" button, then building out the lead. Is there anyway to add the "Create Lead" button or some sort of short cut to the Zoho CRM Dashboard to cut out
        • open word file in zoho writer desktop version

          "How can I open a Microsoft Word (.doc or .docx) file in Zoho Writer if I only have the file saved on my computer and Zoho Writer doesn't appear as an option when I try 'Open with'? Is there a way to directly open the .doc file in Zoho Writer?"
        • Generate leads from instagram

          hello i have question. If connect instagram using zoho social, it is possible to get lead from instagram? example if someone send me direct message or comment on my post and then they generate to lead
        • I want to transfer the project created in this account to another account

          Dear Sir I want to transfer the project created in one account to another account
        • Inactive User Auto Response

          We use Zoho One, and we have a couple employees that are no longer with us, but people are still attempting to email them. I'd like an autoresponder to let them no the person is no longer here, and how they can reach us going forward. I saw a similar
        • Weekly Tips : Customize your Compose for a smoother workflow

          You are someone who sends a lot of emails, but half the sections in the composer just get in your way — like fields you never use or sections that clutter the space. You find yourself always hunting for the same few formatting tools, and the layout just
        • Problem Management Module

          I am looking for a Problem Management module within Zoho Desk. I saw in some training videos that this is available, and some even provided an annual price for it. I want an official confirmation on whether this is indeed available. This is not a particularly
        • Zoho Slowness - Workarounds

          Hi all, We've been having intermittent slowness and Zoho just asks for same stuff each time but never fix it. It usually just goes away on it's own after a couple weeks. Given that speed is a very important thing for companies to be able to keep up with
        • Custom Bulk Select Button

          Zoho CRM offers the ability to select multiple records and invoke a Custom Button This functionality is missing from Recruit Currently we can only add buttons in the detail page and list But we cannot select Multiple Records and invoke a function with
        • How to create a Zoho CRM report with 2 child modules

          Hi all, Is it possible to create a Zoho CRM report or chart with 2 child modules? After I add the first child module, the + button only adds another parent module. It won't let me add multiple child modules at once. We don't have Zoho Analytics and would
        • Zoho CRM still doesn't let you manage timezones (yearly reminder)

          This is something I have asked repeatedly. I'll ask once again. Suppose that you work in France. Next month you have a trip to Guatemala. You call a contact there, close a meeting, record that meeting in CRM. On the phone, your contact said: "meet me
        • Power of Automation :: Smart Ticket Management Between Zoho Desk and Projects

          Hello Everyone, A custom function is a software code that can be used to automate a process and this allows you to automate a notification, call a webhook, or perform logic immediately after a workflow rule is triggered. This feature helps to automate
        • First day of trying FSM in the field.

          What we found. 1. with out a network connection we were unable to start a service call? 2. if you go to an appointment and then want to add an asset it does not seem possible. 3. disappointed not to be able to actually take a payment from within the app
        • BUG - Google Business Buttons - Add a button to GBP Post

          I am experiencing an issue with the "Add a button" feature when creating posts for my Google Business Profile (GBP) through Zoho Social. When I schedule or publish a GBP post and include a call-to-action button with a specific URL, the post itself publishes
        • Rich text Merge field - Not using font specified in HTML

          I have a rich text merge field in a writer template which is creating a table. I have chosen to use this method instead of a repeat region because I need to specify specific cell background colours which change every time the document is created. The
        • Support for Custom Fonts in Zoho Recruit Career Site and Candidate Portal

          Dear Zoho Recruit Team, I hope you're doing well. We would like to request the ability to use custom fonts in the Zoho Recruit Career Site and Candidate Portal. Currently only the default fonts (Roboto, Lato, and Montserrat) are available. While these
        • 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
        • Trying to export a report to Excel via a deluge script

          I have this code from other posts but it gives me an error of improper statement, due to missing ; at end of line or incomplete expression. Tried lots of variations to no avail. openUrl(https://creatorapp.zoho.com/<username>/<app name>/XLSX/#Report:<reportname>,"same
        • Zoho Reports Duplicating Entries

          I have a custom costing tab with a table where we entre invoices. These are under a Heading (PO Subject) and notes added in the form with different line items. In the reports, I have organised the report to group per PO Subject, with the total of the
        • Need help to create a attach file api

          https://www.zoho.com/crm/developer/docs/api/v8/upload-attachment.html Please help me to create it... It's not working for while. Do you have some example?
        • Export view via deluge.

          Hi, Is it possible to export a view (as a spreadsheet) via deluge? I would like to be able to export a view as a spreadsheet when a user clicks a button. Thanks     
        • how to add subform over sigma in the CRM

          my new module don't have any subform available any way to add this from sigma or from the crm
        • Organization Emails in Email History

          How can I make received Org Emails to show up here?
        • Outdated state in mexico

          Hello Zoho team, the drop down to add the state for customers, when they introduce their state in mexico has a city named “Distrito Federal” that name changed many years ago to “ciudad de mexico”. could you please update this so my clients can find the
        • Support new line in CRM Multiline text field display in Zoho Deluge

          Hi brainstrust, We have a Zoho CRM field which is a Muti Line (Small) field. It has data in it that has a carriage return after each line: When I pull that data in via Deluge, it displays as: I'm hoping a way I can change it from: Freehand : ENABLED Chenille
        • Possible to generate/download Quote PDF using REST API?

          See title. Is there any way after a quote has been created to export to a PDF using a specified template and then download it? Seems like something that should be doable. Is this not supported in the API v2.0?
        • Creating an invoice to be paid in two installments?

          Hi there, I own a small Photographic Services business and have not been able to find a way to fit my billing system into Zoho, or any other Accounting software. The way my payments work is: 1. Customer pays 50% of total price of service to secure their
        • Bug in allowing the user to buy out of stock items

          Hi i want to allow the user to buy out of stock items, according to the commerce documentation if i disable Restrict "Out of stock" purchases it will, but it doesnt work, so i want to know if it had any relation with zoho inventory, and if theres any
        • Zoho CRM Calendar | Custom Buttons

          I'm working with my sales team to make our scheduling process easier for our team. We primary rely on Zoho CRM calendar to organize our events for our sales team. I was wondering if there is a way to add custom button in the Calendar view on events/meeting
        • Replace Lookup fields ID value with their actual name and adding inormation from subforms

          Hi everyone,  I wanted to see if someone smarter than me has managed to find any solutions to two problems we have. I will explain both below.  To start we are syncing data from Zoho CRM to Zoho Analytics and I will use the Sales Order module when giving
        • Can a Zoho Sites page be embedded into another website (outside Zoho)

          Hi All, We have a request from a client - they'd like to take one of our information pages created in Zoho Sites and embed it into their own website? I was told through an email with Zoho that this was possible >>Thank you for your patience regarding
        • Next Page