285 words
1 minutes
Dynamically Modify FetchXML Using JavaScript in Dynamics 365 CRM
Dynamically Modify FetchXML Using JavaScript in Dynamics 365 CRM
Recently I got into a requirement to conditionally manipulate the fetchxml’s filter condition on runtime using client-side JavaScript and process the results. Let’s walk through the steps to implement the fetchxml parser logic.
Steps to implement the logic
- Store the required fetchXML query in a variable
fetchQuery. - Parse it as XML.
- Check if a
<filter>node already exists inside the<entity>node. - If it exists, append a new
<condition>node inside the existing<filter>node. - If it doesn’t, create a new
<filter>node, add your<condition>node to it, and append it to the<entity>node.
Parse the FetchXML string
var fetchQuery = "YOUR_FETCHXML";
var myParser = new DOMParser();
var parsedXML = myParser.parseFromString(fetchQuery, "text/xml");This converts the FetchXML string into an parsedXML object that can be manipulated.
Create a new <condition> node
var newConditionNode = document.createElement("condition");
newConditionNode.setAttribute("attribute", "quoteid");
newConditionNode.setAttribute("operator", "eq");
newConditionNode.setAttribute("value", quoteId);This condition filters records where quoteid == quoteId.
If a <filter> node exists, append the condition node to it.
var filterTagFoundFlag = false;
parsedXML.getElementsByTagName("entity")[0].childNodes.forEach(function (xmlnode) {
if (xmlnode.tagName == "filter") {
filterTagFoundFlag = true;
xmlnode.appendChild(newConditionNode);
}
});If no <filter> node was found, create a new node, add the condition to the new node using appendChild(), and append it to the <entity>.
if (filterTagFoundFlag == false) {
var newFilterNode = document.createElement("filter");
newFilterNode.setAttribute("type", "and");
newFilterNode.appendChild(newConditionNode);
parsedXML.getElementsByTagName("entity")[0].appendChild(newFilterNode);
}Rebuild the FetchXML string and remove unwanted namespace attributes
var myResultQuery = parsedXML.documentElement.outerHTML.replaceAll('xmlns="http://www.w3.org/1999/xhtml"', "");Usage of this code
I have implemented a very basic sample to append filter condition to the fetchxml which can be extended to implement complex solutions and I hope this solution might be useful for below scenarios.
- When building dynamic queries based on user inputs
- Reusing same filters for dynamic reports, Form scripts, Subgrid filters etc
- Ribbon button JavaScript
- Custom Web resources, PCF Controls when dynamic filtering is required
Dynamically Modify FetchXML Using JavaScript in Dynamics 365 CRM
https://crmte.ch/posts/fetchxmlonruntime/