WEB API- Part 6 : Create record

Create record using WEB API 

Following code shows how to create an Account record using WEB API and how to set different types of fields

function CreateAccount() {
 
    var serverURL = Xrm.Page.context.getClientUrl();
    var account = {};
    account["name"] = "New Account";
   
   
 //Set LookUp
    account["primarycontactid"] = {
        "firstname": "Sample",
        "lastname": "Contact"
    };// this will create new contact ,if you need to link an existing contact use the following
 //account["primarycontactid@odata.bind"]="/contacts(contactId)"; 
 
    //optionset
    account["companytype"] = 2;
    //two options
    account["donotemail"] = true;
    //number
    account["numberofemployees"] = 30;
 
    var req = new XMLHttpRequest();
    req.open("POST", serverURL + "/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.onreadystatechange = function() {
        if (this.readyState == 4 /* complete */ ) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                var NewAccount = this.getResponseHeader("OData-EntityId");
                var NewAccountId = NewAccount.substr(NewAccount.length - 38).substring(1, 37); 
                Xrm.Utility.openEntityForm("account", NewAccountId); //Open newly created account record
            } else {
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };
    req.send(JSON.stringify(account));
}

 

Please note following code for setting an existing lookup value

 account["primarycontactid@odata.bind"]="/contacts(contactId)";

“contacts” is plural name for contact entity .

var NewAccount = this.getResponseHeader(“OData-EntityId”);  will give  you the newly created record…

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s