To demonstrate, I’ve created an HTML web resource with 1 button on the contact form. When clicking on the button, I will ask the contacts to get a list of all the contacts under the account hierarchy.
After clicking on the Parent Account button, we will get a list of all Contacts under the Account hierarchy. Please check the below Image. It will be the output of our development. Now to get this output, what we need to do in the HTML file, is that I am going to explain.
Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Services Online 2015 Update introduce the capability to define specific self-referencing one-to-many entity relationships as hierarchical. You can write queries that return related data in these hierarchies.
With Web API in MS CRM, we retrieve data using FetchXML. An easy way to construct FetchXML queries is using the advanced find in CRM, you can create queries in advanced find, add columns, define sorting, and then download FetchXML.
Once your FetchXML is ready, you can use this FetchXML in web API to retrieve data from CRM. Here is a sample code for how to execute FetXML and get values from the FetchXML result set. Please note that we need to pass the Top most Account ID of the hierarchy (Main/Root Account). If you can’t have that Root Account ID with you, I will explain to you how to get that using any Account Id you have later in this blog as well.
Now define the FetchXML and web API as below:
So the execution of the above code will show you the output as I showed in the above image. It will list down all Contacts we have about all Accounts of that hierarchy.
If you want to test your fetch XML before development. You can use the “FetchXML Tester” tool from XrmToolBox, you can put your query there and click on Execute.
Now, you click on the Response button and it will show something like this to get all contact records of all accounts in the hierarchy of the Main Account you passed.
Now many of you will have a question, how to get a root account ID if you have an account hierarchy. It’s easy to get with FetchXML and Web API. If you have an account ID for that hierarchy, use it in the FetchXML query below.
You will get the below output after executing this query. You can even integrate this into our code in the same way as I did for the contacts above.