Filter SubGrid in Dynamics 365 (with New Form Rendering or Turbo Form)

Recently we had a requirement wherein we wanted to see all the child records of a record in a SubGrid .

We had self-referential (hierarchical relationship) enabled for that entity.

Configuring the Sub Grid on the form.

We have also enabled the Editable grid for the Sub Grid.

The JavaScript code


function filterSubGrid()
{
// get the current record's guid
var entityId = Xrm.Page.data.entity.getId();

// refer the subgrid
var testGrid = window.parent.document.getElementById("Test");

if (testGrid == null)
{
setTimeout(function () {filterSubGrid(); }, 2000);
return;
}

// fetch xml code using User operator
var fetchXml = "<fetch distinct='false' no-lock='false' mapping='logical'>" +
"<entity name='new_test' >" +
"<attribute name='new_name' />" +
" <attribute name='new_testname' />" +
"<order attribute='new_name' descending='true' />" +
"<filter type='and'>" +
"<condition attribute='new_testid' operator='under' value='"+entityId+"'"+"/>" +
"</filter>" +
"</entity>" +
"</fetch>";

if (testGrid.control != null)
{
testGrid.control.SetParameter("fetchXml", fetchXml);
testGrid.control.refresh();
}
else
{
setTimeout(filterSubGrid, 500);
}
}

The filtered Sub Grid (editable)

Note :- The JavaScript code is unsupported as we are making use of getElementById instead of Xrm library to access subgrid.

Hope it helps..