Following is detail sample code to create a record 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
entityObject: entityObject is an object that of entity contians fields and values that needed to be create.
e.g
var entityObject = {};
entityObject["originatingleadid@odata.bind"] = "/leads(" + guid + ")"; // lookup
contact["firstname"] = string value; // Single line of text
contact["po_preferredlanguage"] = string value; //Option set
contact["donotemail"] = true/false //two Option
*/
function createRecord(entityPlurarName, entityObject) {
var id = null;
var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityPlurarName, false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.send(JSON.stringify(entityObject));
if (req.readyState === 4) {
if (req.status === 204) {
var uri = req.getResponseHeader("OData-EntityId");
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(uri);
id = matches[1];
}
else {
var error = JSON.parse(req.response).error;
Xrm.Utility.alertDialog(error.message);
}
}
return id;
}
You can call the create record method as:
var account = {};
account["primarycontactid@odata.bind"] = "/contacts(" + removeCurlyBraces(Xrm.Page.getAttribute("primarycontactid").getValue()[0].id) + ")"; // lookup
account["name"] = "Test Account name"; // Single line of text
account["paymenttermscode"] = "1";//Text(Net 30) //Option set
account["creditonhold"] = true; //two Option
var accountid=createRecord("accounts", account);
Leave a Reply