Retrieve Multiple through fetch XML using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 


Following is a detail sample code to retrieve multiple records using fetchXml query using Web API in Dynamics CRM.
/*
entityPlurarName: entityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
fetchXml: fetchXml
return:- entity collections object      
*/
 function executeFetchXml(entityPlurarName, fetchXml) {
    var data = null;
    var req = new XMLHttpRequest();
    req.open('GET', Xrm.Page.context.getClientUrl() + "/api/data/v8.1/" + entityPlurarName + "?fetchXml=" + encodeURIComponent(fetchXml), false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.send();
    if (req.readyState === 4) {
        if (req.status === 200) {
            data = JSON.parse(req.response);
        }
        else {
            var error = JSON.parse(req.response).error;
            console.log(error.message);
        }
    }
    return data;
}
You can call the executeFetchXml method as:
 var fetchXml = " <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                " <entity name='account'>" +
                " <attribute name='name' />" +
                " <attribute name='primarycontactid' />" +
                " <attribute name='telephone1' />" +
                " <attribute name='accountid' />" +
                " <order attribute='name' descending='false' />" +
                " <filter type='and'>" +
                " <condition attribute='modifiedon' operator='last-seven-days' />" +
                " </filter>" +
                " </entity>" +
                " </fetch>";
    var data = executeFetchXml('accounts', fetchXml);
    if (data !== null && data.value.length > 0) {
        console.log("Account Name :" + data.value[0].name);
        //you code here
    }


No comments:

Post a Comment