Friday, July 4, 2014

Filter Sub Grid control based on value selected in lookup field in CRM 2013


If you are planning to filter Sub Grid based on the value selected in look up field or change of look up field value, then this bog will help to achieve this customization in CRM 2013.
To demonstrate, I have created one look up field of type Account and Sub Grid that shows Contact records based on Account set in look up field.
 
Requirement is to filter the sub grid so as to show only contact records based on the value selected in Account look up field.
This need to be achieved by client side scripting, below JS function will filter the sub grid based on look up field value (Display contact records that are associated to account selected in look up field).

function FilterSubgrid() {
    var filterId = null;
    var accountLookupObject = Xrm.Page.getAttribute('new_account').getValue();  // get look up field value 

    if (accountLookupObject != null) {
        accountLookupObject[0].name; // text of lookup
        filterId = accountLookupObject[0].id; // Guid of lookup
    }

    var subgridnameObject = document.getElementById("Contacts");   // Contacts is the name of the sub grid on the form 

    if (subgridnameObject == null || subgridnameObject.readyState != "complete") {
        setTimeout(function () { FilterSubgrid(); }, 100);
        return;
    } 

    if (filterId == null) return; 

    // Fetch xml for retrieving filtered contacts based on primary customer

    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";

    fetchXml += "<entity name='contact'>";

    fetchXml += "<attribute name='fullname'/>";

    fetchXml += "<attribute name='telephone1'/>";

    fetchXml += "<attribute name='contactid'/>";   

    fetchXml += "<order attribute='fullname' descending='false' />";

    fetchXml += "<filter type='and'>";

    fetchXml += "<condition attribute='parentcustomerid' operator='eq' uitype='account' value='"+filterId+"' />";

    fetchXml += "</filter>";

    fetchXml += "</entity>";

    fetchXml += "</fetch>"; 

    subgridnameObject.control.SetParameter("fetchXml", fetchXml);

    subgridnameObject.control.refresh();


}

This function need to be used on form load as well as on change of look up field value.

No comments:

Post a Comment