DYNAMICS 365 HOW TO EXECUTE FETCHXML QUERIES IN WEB.API JAVASCRIPT

In Dynamics 365, you can use WebAPI calls to retrieve data using OData queries. However, when coming to more complex queries, the OData might become complicated to be built if not impossible. Therefore, using FetchXml queries in the WebAPI call is your best option.

Querying using FetchXml have more advantages from the easiness to be generated using the Advanced Find and more readable, to using joins and aggregations.

In this quick post, we will see how to execute FetchXml query using Xrm.WebApi in JavaScript.

  1. Prepare the FetchXml you want to execute whether from the Advanced Find, or any other FetchXml generator in the community
  2. Prepare the JavaScript function you want to call in order to execute WebAPI request
  3. The below function is used to retrieve the user roles

    function getUserRoles(context) {
    var formContext = context.getFormContext();
    var userRoles = "";
    var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">';
    fetchXml += '<entity name="role">';
    fetchXml += '<attribute name="name"/>';
    fetchXml += '<attribute name="roleid"/>';
    fetchXml += '<order attribute="name" descending="false" />';
    fetchXml += '<link-entity name="systemuserroles" from="roleid" to="roleid" visible="false" intersect="true" >';
    fetchXml += '<filter type="and" >';
    fetchXml += '<condition attribute="systemuserid" operator="eq" value="' + formContext.context.getUserId() + '" />';
    fetchXml += '</filter>';
    fetchXml += '</link-entity>';
    fetchXml += '</entity>';
    fetchXml += '</fetch>';
    var encodedFetchXML = encodeURIComponent(fetchXml);
    var fetchXmlRequest = "?fetchXml=" + encodedFetchXML;
    Xrm.WebApi.retrieveMultipleRecords("role", fetchXmlRequest).then(
    function success(result) {
    for (const record of result.entities) {
    userRoles +=record.name + "; ";
    }
    },
    function (error) {
    var alertMessage={ text: error.message };
    Xrm.Navigation.openAlertDialog(alertMessage, null);
    }
    );
    }
  4. The two main things to note when using FetchXml in WebAPI calls are
    • Encode the FetchXml query using the encodeURIComponent function
    • Specify that the query you are executing is a fetchXml format in the Xrm.WebApi.retrieveMultipleRecords request


Hope This Helps!

Comments

Popular posts from this blog

DYNAMICS 365 HOW TO HIDE RECENT RECORDS FOR LOOKUP FIELD IN UCI

SEARCH BY GUID IN DYNAMICS 365

SAVE FORM IN DYNAMICS 365 JAVASCRIPT