In our day to day tasks related to dynamics 365 CRM, sometimes we need to filter Subgrid dynamically (placed on an entity form) based on data of some fields on the form. In this article, I am going to explain the same using JavaScript code.

Suppose the Subgrid name is “Booking”. This grid load records from an entity “bookable resource booking”. Our requirement was to filter this grid on the fly based on specific category value selected from an option set named “Category”. Here is the complete code.

function filterBookingsGrid(executionContext) {
    //---Get the form context using execution context
    var formContext = executionContext.getFormContext();

    //---Suppose there is a subgrid named "Booking" placed on your entity's form
    var conSubGrid = formContext.getControl("Booking");

    var category = null;
    if (formContext.getAttribute("new_category").getValue() != null) {
        category = formContext.getAttribute("new_category").getValue()[0].id.replace("}", "").replace("{", "");
    }

    //Create FetchXML for sub grid to filter records

    //Set Grid to Empty if Technician is Null
    var fetchXml = ''
                + '  '
                + '    '
                + '    '
                + '    '
                + '      '
                + '    '
                + '  '
                + '';

    if (category != null) {
        //Show Related Scheduled Bookings
        fetchXml = ' '
                    + ''
                        + ''
                        + '    '
                        + '    '
                        + '        '
                        + '        '
                        + '    '
                        + ''
                        + ''
                        + ''
                        + ' '
                    + ' ';
    }
    formContext.getControl("Booking").getGrid().setParameter("fetchXml", fetchXml);

    //Refresh grid to show filtered records only.
    formContext.ui.controls.get("Booking").refresh();
}