195 words
1 minutes
JavaScript Snippets to Manage Subgrid in Dynamics 365 CRM

Retrieve Subgrid Control:#

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

Get Selected Record IDs in Subgrid:#

var selectedRecords = subgridControl.getGrid().getSelectedRows();

selectedRecords.forEach(function (row) {
    var recordId = row.getData().getEntity().getId(); // This returns the record GUID"

});

Refresh Subgrid:#

subgridControl.refresh();

Hide/Show Subgrid:#

subgridControl.setVisible(false); // Hide
subgridControl.setVisible(true);  // Show

Get Total Record Count in Subgrid:#

var totalRecordCount = subgridControl.getGrid().getTotalRecordCount();

Add Event Handler to Subgrid:#

subgridControl.addOnLoad(function () {
    // Custom logic
});

💡 Make sure the subgrid is already loaded before you try to add addOnLoad. If you are adding this in formContext onLoad, you might have to add a delay till the subgrid control is available via formContext.


Save Event Handling#

Trigger Function on Save:#

function onSaveHandler(executionContext) {
    var eventArgs = executionContext.getEventArgs();

    // SaveMode values: 1 - Save, 70 - AutoSave
    if (eventArgs.getSaveMode() === 1 || eventArgs.getSaveMode() === 70) {
        // Custom logic
    }
}

💡Attach this in the form designer or via formContext.data.entity.addOnSave if needed.

var SaveMode = {
    Save: 1,
    AutoSave: 70,
    SaveAndClose: 2,
    SaveAndNew: 59
};

Prevent AutoSave:#

function preventAutoSave(executionContext) {
    var eventArgs = executionContext.getEventArgs();

    if (eventArgs.getSaveMode() === 70) { // 70 is AutoSave
        eventArgs.preventDefault();
    }
}

Get Changed Attributes on Save:#

function getChangedAttributesOnSave(executionContext) {
    var formContext = executionContext.getFormContext();

    formContext.data.entity.attributes.forEach(function (attribute) {
        if (attribute.getIsDirty()) {
            var logicalName = attribute.getName();
            var newValue = attribute.getValue();

            // Custom logic
        }
    });
}

JavaScript Snippets to Manage Subgrid in Dynamics 365 CRM
https://crmte.ch/posts/subgridsnippets/
Author
Anu Prakash
Published at
2025-05-20
License
CC BY-NC-SA 4.0