Monday, 12 August 2013

Sub Grid Custom Filter in MSCRM 2011

function FilterContactsBasedLookUpFiled() {

    var grid = document.getElementById('gridname');

    if (grid == null) {
        setTimeout('FilterContactsBasedOnShipTo()', 2000);
    }
    else {

        var lookupfield = new Array;
        var lookupid = null;

        lookupfield = Xrm.Page.getAttribute("Lookup").getValue();

        if (lookupfield != null) {

            lookupid = lookupfield[0].id;
        }

        //Else the function will return and no code will be executed.

        else {

            return;
        }

        //This method is to ensure that grid is loaded before processing.


        //This is the fetch xml code which will retrieve all the order products related to the order selected for the case.
        var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
        fetchXml += "<entity name='qcg_contact_shipping_address'>";
        fetchXml += " <attribute name='qcg_shippingaddress' />";
        fetchXml += "<attribute name='qcg_role' />";
        fetchXml += "<attribute name='qcg_contact' />";
        fetchXml += "<order attribute='qcg_shippingaddress' descending='false' />";
        fetchXml += "<link-entity name='contact' from='contactid' to='qcg_contact' alias='am'>";
        fetchXml += " <filter type='and'>";
        fetchXml += "  <condition attribute='parentcustomerid' operator='eq'  value='" + lookupid + "' />";
        fetchXml += "</filter>";
        fetchXml += "</link-entity>";
        fetchXml += "</entity>";
        fetchXml += "</fetch>";

        //Setting the fetch xml to the sub grid.

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

        //This statement will refresh the sub grid after making all modifications.

        grid.control.refresh();
    }

}