Update Account record using Jscript
In my example i’m going to Update account entity record in CRM.
To perform an ODATA call, we need to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.
function UpdateAccount() { var accountId = Xrm.Page.data.entity.getId(); var objAccount = new Object(); // set the name of Account objAccount.Name = "Account Updated from jscript"; // set the Primary Contact lookup field objAccount.PrimaryContactId = { Id: '{421E1EE5-500A-E211-B3FA-78E3B508F827}', LogicalName: "contact", Name: 'Adrian Dumitrascu (sample)' }; // set the Address Type optionset field objAccount.Address1_AddressTypeCode = { Value: 2 }; // set the Credit Hold boolean field objAccount.CreditOnHold = true; // Parse the entity object into JSON var jsonEntity = window.JSON.stringify(objAccount); var serverUrl = Xrm.Page.context.getServerUrl(); var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/AccountSet"; var ODataPath = serverUrl + ODATA_ENDPOINT; $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", datatype: "json", url: ODataPath + "(guid'" + accountId + "')", data: jsonEntity, beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE"); }, error: function (xmlHttpRequest, textStatus, errorThrown) { alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown); } }); }
Excellent Example. may I add that the code line,
“var jsonEntity = window.JSON.stringify(objAccount);” may throw an error i.e. JSON is not defined and should be replaced by
“var jsonEntity = top.window.JSON.stringify(objAccount);”
I have a requirement to Update Contact Field from JScript in CRM2013 where I am calling below function, but it doesn’t work. The error says:- ” SDK.JQuery.updateRecord requires the id parameter”.
the alert displays the ContactId as GUID correctly. I also uploaded JSON2/JQuery1.4.1/SDK.JQuery.js and added that library into Contact form library.
Am I missing something here?? Please assist.
function updateContact(ContactId) {
try {
var contact = {};
var customefieldvalue = new Date().toDateString();
contact.customefield = customefieldvalue ;
alert(contact);
alert(ContactId);
alert(customefieldValue);
SDK.JQuery.updateRecord(
ContactId,
contact,
“contact”,
function () {
writeMessage(“The contact record changes were saved”);
deleteContact(ContactId);
},
errorHandler
);
} catch (ex) { alert(‘JavaScript Error In updateContact:’ + ex.description); }
}
function deleteContact(ContactId){
alert(‘delete contact’);
}
function errorHandler(error) {
writeMessage(error.message);
}
//Helper function to write data to this page:
function writeMessage(message) {
$(“” + message + “”).appendTo(output);
}