Auxiliary Force Technology

Power Apps: Use FetchXML Instead of OData In JavaScript

OData is awesome but there are some scenarios in which using FetchXML just makes more sense. For example, when searching NN Relationships. The following code uses FetchXML by encasing the query in the “backtick” character.

This code searches a custom “account_contactNN” many-to-many intersect using an Account ID to find all related Contacts. You may need to replace the “/api/data/v8.2/” portion with your version from “Developer Resources” in your Settings -> Customizations area.

function searchNN(){
var accountID = Xrm.Page.getAttribute("accountid").getValue();

var fetchXML = `<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
    <entity name='contact'>
        <attribute name='contactid' />
        <order attribute='contactid' descending='false' />
        <filter type='and'>
            <condition attribute='statecode' operator='eq' value='0' />
            </filter>
        </filter>
        <link-entity name='account_contactNN' from='contactid' to='contactid' visible='false' intersect='true'>
            <link-entity name='account' from='accountid' to='accountid' alias='ag'>
                <filter type='and'>
                    <condition attribute='accountid' operator='eq' value='` + accountID + `' />
                </filter>
            </link-entity>
        </link-entity>
    </entity>
</fetch>`;

var encodedFetchXML = encodeURIComponent(fetchXML);

var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contacts?fetchXml=" + encodedFetchXML, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 200) {
            var results = JSON.parse(this.response);

            if (results.value.length != 0) {
                [YOUR CODE HERE]
            }
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send();
}

Posted

in

,

by

Tags: