Retrieve Data Using FetchXMLWebAPI With Webresource In Dynamics CRM

Introduction

In Dynamics 365 CRM, for certain requirements data needs to be retrieved to achieve business functionality. As an example, all contact records whose first name starts with V are used for explanation.

Step 1

Login to the required environment and select required solution [Contact Customizations Solution in this case] as shown in the below figure.

Retrieve Data Using FetchXMLWebAPI with Webresource in Dynamics CRM

Step 2

After Step 1, select contact web resource in solution and click on Edit as shown in the below figure.

Retrieve Data Using FetchXMLWebAPI with Webresource in Dynamics CRM

Step 3

After Step 2, to prepare fetchxml we have to open Dynamics CRM environment and navigate to advance find and quickly frame the filtering criteria and click on download fetchxml as shown in the below figure

Retrieve Data Using FetchXMLWebAPI with Webresource in Dynamics CRM

Step 4

After Step 3, open the downloaded fetchxml and copy and paste it under any function in javascript file (Webresource) and prepare a string value like below code

var fetchXml = "<fetch >"+
        "<entity name='contact'>"+
          "<attribute name='fullname' />"+
          "<order attribute='fullname' descending='false' />"+
          "<filter type='and'>"+
            "<condition attribute='fullname' operator='like' value='V%' />"+
          "</filter>"+
        "</entity>"+
      "</fetch>";

As shown in the below figure

Retrieve Data Using FetchXMLWebAPI with Webresource in Dynamics CRM Figure 4

Step 5

After Step 4, now prepare URL to call a CRM API by using API method to get logged in MSD CRM environment URL with the below code

var finalurl = Xrm.Page.context.getClientUrl() + "/api/data/v9.2/contacts?fetchXml="+encodeURI(fetchXml);

As shown in the figure

Retrieve Data Using FetchXMLWebAPI with Webresource in Dynamics CRM

Step 6

After Step 5, we have to frame XMLHttpRequest request and call it asynchronously to get the required contacts that are required with the below code

var data = null;
var isAsync = false;
var req = null;
if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
req.open("GET", finalurl, isAsync);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 200) {
            data = JSON.parse(this.response);
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send();

Step 7

After Step 6, once data variable has values then we can iterate the collection and test it by printing using console log with the following code

for(var i=0;i< data.value.length;i++)
{
   console.log("Full Name : "+data.value[i].fullname);
}

Step 8

After Step 7, final code looks like this

ContosoVaccination.Scripts.ContactForm = {
    handleOnLoad: function(executionContext) {
        console.log('on load - contact form');
        getContacts(executionContext);
    },
    __namespace: true
}

function getContacts(executionContext) {
    let formContext = executionContext.getFormContext();
    if (formContext !== null && formContext != 'undefined') {
        var fetchXml = "<fetch >" + "<entity name='contact'>" + "<attribute name='fullname' />" + "<order attribute='fullname' descending='false' />" + "<filter type='and'>" + "<condition attribute='fullname' operator='like' value='V%' />" + "</filter>" + "</entity>" + "</fetch>";
        var finalurl = Xrm.Page.context.getClientUrl() + "/api/data/v9.2/contacts?fetchXml=" + encodeURI(fetchXml);
        var data = null;
        var isAsync = false;
        var req = null;
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        req.open("GET", finalurl, isAsync);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
        req.onreadystatechange = function() {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    data = JSON.parse(this.response);
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
        for (var i = 0; i < data.value.length; i++) {
            console.log("Full Name : " + data.value[i].fullname);
        }
    }
}

Step 9

After Step 8, save and publish webresource and register this webresource on onload event of contact form and open any contact record and observe console log window for the required contacts which starts with V letter as shown in the below figure.

Retrieve Data Using FetchXMLWebAPI with Webresource in Dynamics CRM

Note

  1. Make sure to publish all customizations and upload JavaScript (js) file.
  2. Make sure the fetchxml string was well formed or not otherwise lead into errors.
  3. As my concentration is on explaining way to fetch data I have not explained way to register onload event in contact form.

Conclusion

In this way, one can easily fetch contacts data using fetchxml using CRM Web API using webresource.


Similar Articles