Retrieve Record 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 detail sample code to retrieve a record using Web API in Dynamics CRM.
/*
entityName: entityName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
entityId: Guid of entity record
return:-Entity record       
*/
function retrieveEntityById(entityName, entityId) {
    entityId = entityId.replace('{', '').replace('}', '');
    var data = null;
    var req = new XMLHttpRequest();
    req.open('GET', Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityName + "(" + entityId + ")", false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Prefer", "odata.include-annotations=*");
    req.send();
    if (req.readyState == 4 /* complete */) {
        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 retrieve record method as:
var accountId=Xrm.Page.data.entity.getId();
var account=retrieveEntityById("accounts",accountId);
if(account!=null)
var accountName=account.name;
var accountNumber=account.accountnumber;

No comments:

Post a Comment