JScript to Create record and its related record using Web API – CRM 2016
Below is the script snippet to create ‘Account’ record using Web API.
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 = “Rajeev Associates”;
objAccount.creditonhold = false;
objAccount.accountcategorycode = 1;
objAccount.revenue = 123456;// Create new Contact and Set as ‘Primary Contact’
objAccount.primarycontactid = {};
objAccount.primarycontactid.firstname = “Hello”;
objAccount.primarycontactid.lastname = “Lobo”;// 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);
}
- To set the lookup you need to fetch the Contact GUID first and set to ‘primarycontactid@odata.bind’. ‘@odata.bind’ is suffix and ‘primarycontactid‘ is the schema name of lookup.
- Below is sample script to retrieve Contact GUID by Fullname
function getPrimaryContact() {
var clientUrl = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest();
req.open(“GET”, encodeURI(clientUrl + “/api/data/v8.0/contacts?$select=fullname&$filter=fullname eq ‘John Miller'”), 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;
if (contactId) {Xrm.Utility.alertDialog(“Contact ID : ” + contactId);
}
}
}
else {
var error = JSON.parse(this.response).error;
alert(“Error retrieving contact – ” + error.message);
}
}
};req.send();
}
🙂