For ex. To demonstrate, I created a HTML web resource with 1 button on Contact form. While clicking on button, I will query contacts to get list of all contacts under the Account hierarchy.
After clicking on Parent Account button, we will get a list of all Contacts under the Account hierarchy. Please check below Image. It will be the output of our development. Now to get this output, what we need to do in HTML file, that I am going to explain.
Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Services Online 2015 Update introduces 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 are retrieve data using FetchXML. Easy way to construct FetchXML queries are using advanced find in CRM, you can create query 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 sample code for how to execute FetXML and get values from FetchXML result set. Please Note that, we need to pass the Top most Account ID of hierarchy (Main/Root Account). If you can't have that Root Account ID with you, I will explain 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 execution of above code will show you output as I shown in above Image. It will list down all Contacts we have in relation of all Accounts of that hierarchy.
If you want to test your fetch xml before development. You can use "FetchXML Tester" tool from XrmToolBox, you can simply put your query there and click on Execute.
Now, you click on Response button and it will show something like this to get all contact records of all accounts in hierarchy of the Main Account you passed.
Now many of you will have a question, how you can get the Root Account ID if the Account Hierarchy. Well with FetchXML and Web API it's pretty easy to get. If you have any Account Id of that Hierarchy then just use this in below FetchXML query.
You will get below output after executing this query. You can even integrate this on our code with same way like I did for contacts above.