web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Suggested answer

Trigger a flow on adding a new row to a subgrid in a different tab on CRM form

(2) ShareShare
ReportReport
Posted on by 84
Hi
I have a subgrid on separate tab on the form. I want to trigger a flow on add or removal a row on this subgrid.
 
I read many posts which suggest adding an "addOnLoad" event to the subgrid.  Which gets triggered automatically when subgrid refreshes on load. 
 
I am not able to access the grid by its name, as the tab where subgrid is set has many sections and I have to loop through those sections to access the subgrid control object. 
 
When I get the grid object when I add the addOnLoad event I am seeing error like "grid.addOnLoad" is not a function 
 
Here is my code: on the Onload event of the form I am adding this code 
 
var tabClients=Crm.Context.ui.tabs.get("tab_clients");
            
 tabClients.sections.forEach(function (section, sectionIndex)
            {
                if (section.controls._collection!=null && section.controls.getByName("ClientWorkers")!=null)
                {
                    var grid =section.controls.getByName("ClientWorkers").getGrid();
                    grid.addOnload(ClientgridOnLoad);    (this line is giving error)                                                                       
                }            
            });       
 
ClientgridOnLoad:function(){        
        setTimeout(()=>
        {
           Some code here             
        }, 5000);            
    },
 
When I debug the javascript I don't see any prototype function like "addOnLoad"
I just see functions like getRows(), getTotalRecordCount() etc. 
 
 
Appreciate if anyone can help me on this. 
 
Thanks 
Nalina
 
Categories:
I have the same question (0)
  • Suggested answer
    Saif Ali Sabri Profile Picture
    2,346 Super User 2025 Season 2 on at
    Trigger a flow on adding a new row to a subgrid in a different tab on CRM form

    Triggering a Flow on Subgrid Row Add/Remove in Dynamics 365 CRM

    Issue Summary:

    • You are trying to trigger an event when a row is added/removed from a subgrid that is inside a different tab.
    • The addOnLoad function is not available on getGrid().
    • Standard methods like getRows() and getTotalRecordCount() do not support event listeners.

    Solution Approach

    1. Use addOnLoad on the Subgrid Control (Not getGrid())

    The correct approach is to attach the addOnLoad event directly to the subgrid control, not getGrid(). Modify your code like this:

    javascript 
    function onFormLoad(executionContext) {
    var formContext = executionContext.getFormContext();

    var subgridControl = formContext.getControl("ClientWorkers");

    if (subgridControl) {
    subgridControl.
    addOnLoad(ClientgridOnLoad);
    }
    }


    function ClientgridOnLoad(executionContext) {
    setTimeout(() => {
    console.log("Subgrid reloaded. You can trigger your flow here.");

    // Example: Count rows
    var subgrid = executionContext.getFormContext().getControl("ClientWorkers");
    var rowCount = subgrid.getGrid().getTotalRecordCount();

    console.log("Total rows in subgrid:", rowCount);

    // Add logic to trigger Power Automate flow if needed
    }, 5000);
    }
     

    ✅ Why This Works?

    • addOnLoad() must be called on the subgrid control, not the getGrid() object.
    • It ensures that the function runs whenever the subgrid reloads (which happens when rows are added or removed).
     

    2. Alternative: Trigger Power Automate Flow on Row Changes

    If you want to trigger a Power Automate flow, you can:

    1. Create a Dataverse trigger for row addition/removal in the related table.
    2. Choose "When a row is added, modified, or deleted" as the trigger.
    3. Use conditions to filter only relevant updates.
     
     

    Final Recommendation

    • Use addOnLoad on the subgrid control (as in Solution 1).
    • If Power Automate is needed, use a Dataverse trigger for the related table.

    Would you like further guidance on triggering a Power Automate flow?

  • NV-12080530-0 Profile Picture
    84 on at
    Trigger a flow on adding a new row to a subgrid in a different tab on CRM form
    Hi PatSau, 
    Record is being created in n:n Relationship table. Hence the issue.
    I checked lots of posts, it can be done using JS or to create a webhook which can trigger a flow, for that I have to create an assembly and then a webhook underneath. 
    Thought JS would be simpler than Webhook.
    Thanks
  • Suggested answer
    PatSau Profile Picture
    27 on at
    Trigger a flow on adding a new row to a subgrid in a different tab on CRM form
    Hi, 
     
    I may have missed something here but you are trying to trigger a flow when a record is created from a subgrid in Dynamics 365 and I don't understand why you need to do this in JS. The trigger for the flow should just be that the record has been created. It doesn't matter where it comes from does it? 
     
    My assumption would be that the user is deleting the record when you say remove and there is a trigger fot that as well. If this is not the case then the lookup on the related record would be nulled so you could run the flow on that condition? 
  • NV-12080530-0 Profile Picture
    84 on at
    Trigger a flow on adding a new row to a subgrid in a different tab on CRM form
    Thanks Saif
    I realised getGrid() was not required to access the control's addOnLoad method. 
     
    I have to trigger a flow only on Adding a row. 
     
    Which is not happening. Rest of the code you mentioned in your post I already tried that. 
     
    Thanks again for taking time to respond  
     
     
  • Suggested answer
    Saif Ali Sabri Profile Picture
    2,346 Super User 2025 Season 2 on at
    Trigger a flow on adding a new row to a subgrid in a different tab on CRM form

    My response was crafted with AI assistance, tailored to provide detailed and actionable guidance for your query.

    The issue you are encountering stems from how subgrids work in Dynamics 365 and the misunderstanding of the addOnLoad function's application. In Dynamics 365, the addOnLoad method applies to the subgrid control, not the grid object (the result of getGrid()). Additionally, you are trying to bind the addOnLoad method to the subgrid at the wrong level.

     


    Key Concepts

    1. Subgrid Control vs. Grid Object:

      • The subgrid control (controls.getByName("ClientWorkers")) is the actual control you add addOnLoad to.
      • The grid object (.getGrid()) provides methods to manipulate and retrieve data from the grid but does not allow you to attach addOnLoad events.
    2. Subgrid Events:

      • The addOnLoad method is used to attach an event handler to the subgrid control's refresh event (triggered when the subgrid reloads its data, including after adding or removing rows).
    3. Tab and Subgrid Initialization:

      • If the subgrid is located on a hidden tab, it might not be fully initialized when your form loads. This can cause issues when trying to access its methods or attach event handlers. You may need to explicitly handle this scenario.

    Correct Implementation

    Here’s the corrected implementation of your code:

    Step 1: Add Event Listener to the Subgrid Control

    The addOnLoad method should be called directly on the subgrid control. Here's the corrected code:

    javascript 
    function onFormLoad(executionContext) {
    // Get the form context
    var formContext = executionContext.getFormContext();

    // Access the tab where the subgrid resides
    var tabClients = formContext.ui.tabs.get("tab_clients");

    // Ensure the tab is loaded
    if (tabClients) {
    // Iterate through the sections in the tab
    tabClients.sections.forEach(function (section) {
    // Look for the subgrid control by name
    var clientWorkersControl = section.controls.getByName("ClientWorkers");
    if (clientWorkersControl) {
    // Add the onload event handler to the subgrid control
    clientWorkersControl.addOnLoad(ClientgridOnLoad);
    }
    });
    }
    }

    // Event handler for the subgrid's onload event
    function ClientgridOnLoad(executionContext) {
    setTimeout(() => {
    console.log("Subgrid data has been reloaded.");
    // Add your logic here (e.g., trigger a Power Automate flow)
    }, 5000); // Optional delay to ensure all changes are processed
    }

    Step 2: Ensure the Tab and Subgrid are Initialized

    If the subgrid resides in a hidden tab (e.g., not visible on form load), it won’t be initialized until the tab is activated. In this case, you must use the addTabStateChange method to attach the addOnLoad handler after the tab is loaded.

    javascript 
    function onFormLoad(executionContext) {
    // Get the form context
    var formContext = executionContext.getFormContext();

    // Access the tab where the subgrid resides
    var tabClients = formContext.ui.tabs.get("tab_clients");

    if (tabClients) {
    // Add a tab state change event to handle lazy initialization
    tabClients.addTabStateChange(onTabStateChange);
    }
    }

    // Handle the tab state change (when the tab becomes visible)
    function onTabStateChange(tabContext) {
    if (tabContext.getDisplayState() === "expanded") {
    // Tab is now visible, attach subgrid event handler
    var formContext = tabContext.getParent();
    var tabClients = formContext.ui.tabs.get("tab_clients");

    tabClients.sections.forEach(function (section) {
    var clientWorkersControl = section.controls.getByName("ClientWorkers");
    if (clientWorkersControl) {
    // Add the onload event handler to the subgrid control
    clientWorkersControl.addOnLoad(ClientgridOnLoad);
    }
    });
    }
    }

    // Event handler for the subgrid's onload event
    function ClientgridOnLoad(executionContext) {
    setTimeout(() => {
    console.log("Subgrid data has been reloaded.");
    // Add your logic here
    }, 5000);
    }

    Step 3: Trigger a Power Automate Flow on Subgrid Changes

    If you need to trigger a Power Automate Flow whenever rows are added or removed from the subgrid, you can use the following approach:

    1. Detect Row Changes:

      • While the addOnLoad event refreshes whenever data in the subgrid changes, it doesn’t distinguish between add, remove, or other actions.
      • Use the getGrid().getTotalRecordCount() method to track the number of rows and identify if rows were added or removed.
    2. Trigger the Flow:

      • Use JavaScript to make an HTTP request to Power Automate’s HTTP Trigger or create a plugin that triggers the flow.

    Example:  javascript 

    function ClientgridOnLoad(executionContext) {
    // Access the grid object
    var gridContext = executionContext.getFormContext().getControl("ClientWorkers").getGrid();

    // Track the total record count
    var recordCount = gridContext.getTotalRecordCount();
    console.log("Subgrid Record Count: " + recordCount);

    // Trigger Power Automate Flow if necessary
    if (recordCount > 0) {
    triggerPowerAutomateFlow();
    }
    }

    function triggerPowerAutomateFlow() {
    // Example HTTP call to Power Automate
    var flowUrl = "https://prod-XX.westus.logic.azure.com/workflows/your-flow-id";
    var data = {
    message: "Row added or removed in subgrid",
    timestamp: new Date().toISOString(),
    };

    var req = new XMLHttpRequest();
    req.open("POST", flowUrl, true);
    req.setRequestHeader("Content-Type", "application/json");
    req.send(JSON.stringify(data));

    console.log("Power Automate Flow triggered");
    }

    Key Notes

    1. Initialize Subgrid Properly:

      • Ensure the subgrid is initialized before attaching the addOnLoad handler. Use addTabStateChange for subgrids in hidden tabs.
    2. Track Record Changes:

      • Use the getGrid() and methods like getTotalRecordCount() to monitor row additions/removals.
    3. Triggering a Flow:

      • Use Power Automate’s HTTP trigger to handle events when rows are added or removed. Ensure the flow has the proper endpoint URL and authentication.
    4. Debugging:

      • Use the browser’s developer tools to debug the script. Check if the ClientWorkers control is found and if the addOnLoad event is correctly attached.
  • NV-12080530-0 Profile Picture
    84 on at
    Trigger a flow on adding a new row to a subgrid in a different tab on CRM form
    grid.addOnLoad is now working
     
    There was fault in my code which should be 
     
     var grid =section.controls.getByName("ClientWorkers");
                        grid.addOnload(ClientgridOnLoad); 
     
    However, JS is not triggered when I add a row or remove a row
     
    so the core problem is still there. 
     
    Hoping someone can help on this.
     
    Thanks

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Rishabh Kanaskar Profile Picture

Rishabh Kanaskar 258

#2
MVP-Daniyal Khaleel Profile Picture

MVP-Daniyal Khaleel 174

#3
Tom_Gioielli Profile Picture

Tom_Gioielli 121 Super User 2025 Season 2

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans