The following function could be used to update records in
json/ajax.This could be useful in scenario where we want to update some records
in the background
function updateRecord(id, entityObject, odataSetName) {
//debugger;
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";
//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) {
//alert('Updated successfully');
},
error: function (XmlHttpRequest,
textStatus, errorThrown) {
if (XmlHttpRequest &&
XmlHttpRequest.responseText) {
alert("Error while updating "
+ odataSetName + " ; Error – " +
XmlHttpRequest.responseText);
}
}
});
}
The above function can be called in the following manner,
for eg. if I want to call this function to update a picklist/optionset value on
the incident entity
var caseId = Xrm.Page.data.entity.getId();
var incidentObj = new
Object();
incidentObj.fieldname_optionsettypeoffield = {
Value: 1 };
updateRecord(caseId, incidentObj, "IncidentSet");
Note: This will require json2 and jquery1.4.1.min.js
to be preloaded on your form as shown below
No comments:
Post a Comment