Create record and its related 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.This has some good things, we can create the related records and set them as look up values if we do not have the values.

function createAccount() {
    var clientUrl = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest()
    req.open(“POST”, encodeURI(clientUrl + “/api/data/v8.0/accounts”), 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.setRequestHeader(“Prefer”, “odata.include-annotations=*”);

    // Set Account Object

    var objAccount = {};
    objAccount.name = “My Account”;
    objAccount.creditonhold = false;
    objAccount.accountcategorycode = 1;
    objAccount.revenue = 123456;
    // account[“abc_approvaldate”] = new Date();

    // Create new Contact and Set as ‘Primary Contact’
    objAccount.primarycontactid = {};
    objAccount.primarycontactid.firstname = “I am the Primary”;
    objAccount.primarycontactid.lastname = “Contact”;

    // Set existing Contact as ‘Primary Contact’

    // objAccount[‘primarycontactid@odata.bind’] = “/contacts(” + { contact GUID } + “)”;

    //convert JSON object to string
    var body = JSON.stringify(objAccount);

    req.onreadystatechange = function() {

        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if(this.status == 204) {
                var accountUri = this.getResponseHeader(“OData-EntityId”);
                // Get Account GUID
                var accountID = accountUri.split(/[()]/);
                accountID = accountID[1];
                Xrm.Utility.alertDialog(“Created Account ID : “ + accountID);
            }
        }
    };
    req.send(body);
}

Hope this helps.

Happy CRM’ing
Gopinath

One thought on “Create record and its related record using Web API – CRM 2016

  1. Unknown February 17, 2017 / 11:25 am

    Hi, I am totally new to this and I don't know how to setup up these kind of project. What I have tried is I have created a web page on Microsoft Portal and used this code, But I am getting unauthorized error. Even though I am logged in to the portal. Please Help me with this.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s