Get subgrid data from the database using javascript
Previously I shared how to retrieve Subgrid data from UI. But in CRM the subgrid values may vary from user to user. So if we want all values from that particular entity then we should get the data from the database. For that, we need to generate FetchXML.
Here I am getting all Competitors(Competitor is a subgrid) from related opportunity entity.
Step1: We need to add javascript files from "XrmServiceToolkit".
Here you can download XrmServiceToolkit: https://xrmservicetoolkit.codeplex.com/
Step2: Now go to Sales --> Opportunity Entity--> Advance Finder-->Write your own query here. I attached sample query for getting all competitors related to the current entity.
Step3: Download the fetchXML.
Step4: Change the format of fetchXML.
Step5: Start writing Javascript. Here I add my custom javascript code.
function RetrieveSubgridRecord() {
var Xmlsample =
"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>" +
"<entity name='competitor'>" +
"<attribute name='name' />" +
"<attribute name='websiteurl' />" +
"<attribute name='competitorid' />" +
"<order attribute='name' descending='false' />" +
"<link-entity name='opportunitycompetitors' from='competitorid' to='competitorid' visible='false' intersect='true'>" +
"<link-entity name='opportunity' from='opportunityid' to='opportunityid' alias='am'>" +
"<filter type='and'>" +
"<condition attribute='opportunityid' operator='eq' uitype='opportunity' value='" + Xrm.Page.data.entity.getId() + "' />" + //Xrm.Page.data.entity.getId() gives current entity ID
"</filter>" +
"</link-entity>" +
"</link-entity>" +
"</entity>" +
"</fetch>"
var Records = XrmServiceToolkit.Soap.Fetch(Xmlsample);
alert(Records.length);
//Here you can write your own logic based on your requirement.
Thanks for reading this.Hope it helps you.