Archive

Archive for April 19, 2012

Create record synchronously using OData and JScript in CRM 2011

April 19, 2012 4 comments

Hi,

Below is the Jscript function to create record synchronously using OData and Jscript

function createRecordSync(entityObject, odataSetName) {

var jsonEntity = window.JSON.stringify(entityObject);

// Get Server URL

var serverUrl = Xrm.Page.context.getServerUrl();

//The OData end-point

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var createRecordReq = new XMLHttpRequest();

var ODataPath = serverUrl + ODATA_ENDPOINT;

createRecordReq.open(‘POST’, ODataPath + “/” + odataSetName, false);

createRecordReq.setRequestHeader(“Accept”, “application/json”);

createRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

createRecordReq.send(jsonEntity);

var newRecord = JSON.parse(createRecordReq.responseText).d;

return newRecord;

}

How do I call this method :-

  • Create a new .jscript file (i.e., “account.js”)
  • Copy & Paste above code
  • Add “account.js” as a webresource in CRM
  • Add “Json2.js” & “jquery1.4.1.min.js” helper script files as webresources
  • Get the helper files from CRM 2011 SDk under path “\sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts”
  • To create an “Account”
  • Pass “Account” object, OData Set name (i.e.,AccountSet)

var account = new Object();

account.Name = “Rajeev Pentyala”;

var createdAccount = createRecordSync(account, “AccountSet”);

if (createdAccount) {

alert(“New Account Created !!!; Id – “+createdAccount.AccountId);

}

🙂