Wednesday 6 July 2016

Retrieve record using Web API – CRM 2016

Hi,

We all know with CRM 2016 we should use Web API instead of oData in JavaScript. Here is the sample code for creating a record using Web API.


function getPrimaryContact() {
    var clientUrl = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest();
    req.open("GET", encodeURI(clientUrl + "/api/data/v8.0/contacts?$select=fullname,emailaddress1&$filter=fullname eq 'I am the Primary Contact'"), true);
    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.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                var data = JSON.parse(this.response);
                var dat = data.value;
                // Loop through ‘Contact’ result set
                for (var i = 0; i < dat.length; i++) {
                    // Get ‘Contact ID’ from Contact record.
                    var contactId = dat[i].contactid;
                    var emailAddress = dat[i].emailaddress1;
                    if (contactId) {
                        Xrm.Utility.alertDialog("Email Address : " + emailAddress);
                        // Xrm.Utility.alertDialog("Contact ID : " + contactId);
                    }
                }
            }
            else {
                var error = JSON.parse(this.response).error;
                alert("Error retrieving contact – " + error.message);
            }
        }
    };
    req.send();
}

Hope this helps.
--
Happy CRM'ing

Gopinath

No comments:

Post a Comment