July 16, 2013

How to bind a function to the Sub-Grid refresh event

A common customization requested by customers is to execute some logic when a Sub-Grid is refreshed. Unfortunately the Xrm Object Model doesn't provide a method to bind a function to the refresh event.
To implement this functionality is necessary to use unsupported JavaScript code, paying attention when a new rollup is released.
The following code is compatible with UR12/Polaris update that introduced cross-browser support for CRM 2011.
function AddEventToGridRefresh(gridName, functionToCall) {
   // retrieve the subgrid
   var grid = document.getElementById(gridName);
   // if the subgrid still not available we try again after 1 second
   if (grid == null) {
       setTimeout(function () {AddEventToGridRefresh(gridName, functionToCall);}, 1000);
       return;
   }
   // add the function to the onRefresh event
   grid.control.add_onRefresh(functionToCall);
}
Is possible to use the AddEventToGridRefresh function in two different ways. Assuming to attach the following function:
// function used in this example
function AdviseUser() {
   alert("Sub-Grid refreshed");
}
The function can be called directly passing the parameters inside the dialog box


or inside another JavaScript function:
function OnLoad() {
   AddEventToGridRefresh('accountContactsGrid', AdviseUser);
}
The first parameter is a string and quotation marks are necessary, the second parameter is the name of the function and must be written without quotation marks.

4 comments:

  1. Thanks for posting, this is a good reusable solution.

    ReplyDelete
  2. I have a text field named "Total" and i want to update the field everytime I add or delete an record in sub grid . any solution ?

    Because what you mention above will only work when form is refreshed . and I want something to work when my subgrid is refreshed .

    ReplyDelete
    Replies
    1. as far as I know currently it's not possible

      Delete
  3. This still works with 2015, thanks for sharing!

    ReplyDelete