javascriptcrmmicrosoft-dynamicsdynamics-crm-2015fetchxml

How to display contacts for account and sub-account in Dynamics CRM


I am sharing this because it took me forever to find a good way to display all contacts for a parent account and all it's sub-accounts. So that when looking at a child account it will show only contacts for that account but for the head account, it will show contacts for that account as well as contacts for its child accounts.


Solution

  • First insert a subgrid for contacts in the account form editor, name it, give it a label to display. Have the options like the picture below.

    Subgrid options

    Then add the code below as a web resource (JavaScript)

    function GetContacts() {
    
    // get Contacts Sub grid
    var accountChildContactsGrid = window.parent.document.getElementById("whatever your sub grid name is")
    
    
    // Get the ID of the current account
    var rootAccountID = Xrm.Page.data.entity.getId();
    
    // Check that the subgrid is ready
    if (accountChildContactsGrid == null){
        setTimeout('GetContacts()',1000);
        return;
    }
    
    // Construct FetchXML for contacts in this account and its child accounts
    var fetchXml = "<fetch version='1.0' mapping='logical'>";
    fetchXml += "<entity name='contact'>";
    fetchXml += "<attribute name='fullname'/>";
    fetchXml += "<attribute name='emailaddress1'/>";
    fetchXml += "<order attribute='fullname' descending='false' />";
    fetchXml += "<link-entity name='account' from='accountid' to='parentcustomerid' link-type='inner' >";
    fetchXml += "<filter type='and'>";
    fetchXml += "<condition attribute='accountid' operator='eq-or-under' value='" + rootAccountID + "' />";
    fetchXml += "<condition attribute='accountid' operator='not-null' />";
    fetchXml += "</filter>";
    fetchXml += "</link-entity>";
    fetchXml += "</entity>";
    fetchXml += "</fetch>";
    
    // make sure control is ready and set data and refresh the subgrid
    if (accountChildContactsGrid.control != null){  
        accountChildContactsGrid.control.SetParameter("fetchXml", fetchXml);
        accountChildContactsGrid.control.refresh();
    }
    else{
        setTimeout('GetContacts()',1000);
    }
    

    }

    Finally, back in the account form editor go to form properties and add the resource to the library and add an onload action that will call our GetContacts() function as per the image below

    enter image description here

    I hope this helps someone

    Note: this solution is for Dynamics CRM Online 2015 (7.1) Note2: you will need to have a hierarchical relationship capability already set up for this to function