CALL JAVASCRIPT FUNCTION ON SUBGRID REFRESH IN DYNAMICS 365

In this post, we will see an example on how to call JavaScript function when a subgrid is refreshed in Dynamics 365.

Sometimes, you have a scenario where you need to call a JavaScript function when a sub-grid refresh event has occurred in the form.

The subgrid refresh event might happen if a record is added to the subgrid, deleted from the subgrid, or the refresh button of the subgrid is clicked.

  1. In order to trigger the function, you have to register a function on the OnLoad event of the form (in the below exemple manageFormBasedOnRecordsInSubgrid) which in turns, will call the OnLoad event of the subgrid
  2. After doing this, each time you add/delete record from sub-grid, the function functionTriggerredgetOnSubgridRefresh() will be triggered.
  3. Below, is a sample code for the function that will be called when the subgrid is refreshed
    var formContext;
    var gridContext;
    function manageFormBasedOnRecordsInSubgrid(context) {
    formContext = context.getFormContext();
    gridContext = formContext.getControl("Contacts");
    //ensure that the subgrid is ready…if not wait and call this function again
    if (gridContext == null) {
    setTimeout(function () { manageFieldsBasedOnLivrableSubgrid(); }, 500);
    return;
    }
    //bind the event listener when the subgrid is ready
    gridContext.addOnLoad(functionTriggeredgetOnSubgridRefresh);
    }

    function functionTriggeredgetOnSubgridRefresh() {
    try {
    setTimeout(function () {
    if (gridContext != null && gridContext != undefined) {
    var recordsCount = formContext.getControl("Contacts").getGrid().getTotalRecordCount();
    if (recordsCount > 0) {
    var alertMessage = { text: "Do something here when subgrid contains records" };
    Xrm.Navigation.openAlertDialog(alertMessage, null);
    }
    else {
    var alertMessage = { text: "Do something here when subgrid has no records" };
    Xrm.Navigation.openAlertDialog(alertMessage, null);
    }
    }
    }, 1000);
    }
    catch (e) {
    var alertMessage = { text: "getTotalGridRecordCount Error: " + e.message || e.description };
    Xrm.Navigation.openAlertDialog(alertMessage, null);
    }
    }
    Sub grid refresh 1

    Sub grid refresh 2


Hope This Helps!

Comments

Popular posts from this blog

DYNAMICS 365 HOW TO HIDE RECENT RECORDS FOR LOOKUP FIELD IN UCI

SEARCH BY GUID IN DYNAMICS 365

SAVE FORM IN DYNAMICS 365 JAVASCRIPT