CRM 2011 JQuery OData REST Endpoints Create Record

CRM 2011 JQuery OData REST Endpoints Create Record

In CRM 2011, we can create record easily using JQuery and OData. This will get triggered asynchronously using the ajax functionality.
Create Record function from the SDK:

function createRecord(entityObject, odataSetName, successCallback, errorCallback) {

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

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

//entityObject is required

if (!entityObject) {

alert(“entityObject is required.”);

return;

}

//odataSetName is required, i.e. “AccountSet”

if (!odataSetName) {

alert(“odataSetName is required.”);

return;

}

//Parse the entity object into JSON

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

//Asynchronous AJAX function to Create a CRM record using OData

$.ajax({

type: “POST”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName,

data: jsonEntity,

beforeSend: function (XMLHttpRequest) {

//Specifying this header ensures that the results will be returned as JSON.

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

},

success: function (data, textStatus, XmlHttpRequest) {

if (successCallback) {

successCallback(data.d, textStatus, XmlHttpRequest);

}

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

if (errorCallback)

errorCallback(XmlHttpRequest, textStatus, errorThrown);

else

errorHandler(XmlHttpRequest, textStatus, errorThrown);

}

});

}

function errorHandler(xmlHttpRequest, textStatus, errorThrow) {

alert(“Error : ” + textStatus + “: ” + xmlHttpRequest.statusText);

}

To create new record, you just need to instantiate your object and call the function. The tricky part is when you want to assign Lookup field or OptionSetValue. You can get more info on this from the SDK itself. Here is an example

var opportunity = {

CustomerId: {

__metadata: { type: “Microsoft.Crm.Sdk.Data.Services.EntityReference” },

Id: <lookup record id>,

LogicalName: <lookup record logical name>

},

new_tonnageloss: “0”,

new_originaltonnage: “100”

};

createRecord(opportunity, “OpportunitySet”, createOpportunityCompleted, null);

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