Here we are going to update Optionset and Lookup fields using Odata Service in CRM 2011. In the SDK sample you will find only to update Text fields. After spending some time on Odata service, i got the solution to update Option set and Lookup fields.
Here i am going to update Account information using Odata service.
function updateOptionset() {
// Gets the record Guid
// Gets the record Guid
var id = Xrm.Page.data.entity.getId();
var changes = {
// Text field
// Text field
Telephone1: "123456789",
// Option set field
// Option set field
Address1_AddressTypeCode: { Value: 3 },
// Lookup field
// Lookup field
ParentAccountId: {
Id: "8F8338A9-9AB2-E011-9E6D-000C29B0167C", // Guid of the parent account
LogicalName: "account"
}
};
//updateRecord exists in JQueryRESTDataOperationFunctions.js
updateRecord(id, changes, "AccountSet", updateAccountCompleted, null);
}
function updateRecord(id, entityObject, odataSetName, successCallback, errorCallback) {
var context = Xrm.Page.context;
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
//id is required
if (!id) {
alert("record id 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 Update a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: jsonEntity,
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
//Specify the HTTP method MERGE to update just the changes you are submitting.
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (data, textStatus, XmlHttpRequest) {
//The MERGE does not return any data at all, so we'll add the id
//onto the data object so it can be leveraged in a Callback. When data
//is used in the callback function, the field will be named generically, "id"
data = new Object();
data.id = id;
if (successCallback) {
successCallback(data, 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);
}
//Called upon successful Account update.
function updateAccountCompleted(data, textStatus, XmlHttpRequest) {
//Get back the Account JSON object
var account = data;
alert("Account updated: id = " + account.id);
}
Hope it helps!!!!