Tuesday, May 28, 2013

Filter Sub Grid using JavaScript in CRM 2011

Please follow bellow steps to filter sub grid using JavaScript
1. Create FetchXML from Advance find view that you want to set in Sub Grid.
2. Note down the Grid Unique name (We need this in below JavaScript)

Copy the below JavaScript and made changes in BOLD section.

function updateSubGrid() {
    //This will get the related products grid details and store in a variable.
    var relatedAccounts = document.getElementById("YourGridName"); // Your Grid Unique Name
    //Initializing the lookup field to store in an array.
    var lookupfield = new Array;
    //Get the lookup field
    lookupfield = Xrm.Page.getAttribute("contactid").getValue(); // Filter Grid base on the lookup value
    //This will get the lookup field guid if there is value present in the lookup
    if (lookupfield != null) {
        var lookupid = lookupfield[0].id;
    //Else the function will return and no code will be executed.
    else {
    //This method is to ensure that grid is loaded before processing.
    if (relatedAccounts == null || relatedAccounts.readyState != "complete") {
        //This statement is used to wait for 2 seconds and recall the function until the grid is loaded.
        setTimeout('updateSubGrid()', 2000);


    //This is the fetch xml code which display all the account associated with the contact.
    //Good Practice is to create FetchXML from Advance Find View and Make formating as mentioned below

    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
    fetchXml += "<entity name='account'>";
    fetchXml += "<attribute name='fullname' />";
    fetchXml += "<attribute name='boardname' />";
    fetchXml += "<attribute name='contactidid' />";
    fetchXml += "<order attribute='appointeestage' descending='false' />";
    fetchXml += "<filter type='and'>";
    fetchXml += "<condition attribute='statecode' operator='eq' value='0' />";
    fetchXml += "<condition attribute='contactid' operator='eq' uitype='contact' value='" + lookupid + "' />";
    fetchXml += "</filter>";
    fetchXml += "</entity>";
    fetchXml += "</fetch>";

    //Setting the fetch xml to the sub grid.
    relatedAccounts.control.setParameter("fetchXml", fetchXml);
    //This statement will refresh the sub grid after making all modifications.


Call updateSubGrid function onload of the form and publish the customization.
I hope it helps someone :)