Thursday 31 December 2015

MS CRM 2016 Web API Operations - Basic Update



Basic Update:

In the last post I have created an Account using Web API call. Here we will update the created Account. Update operations use the HTTP PATCH verb. Pass a JSON object containing the properties you want to update to the URI that represents the entity. A response with a status of 204 will be returned if the update is successful.

Note: 

When updating an entity, only include the properties you are changing in the request body. Simply updating the properties of an entity that you previously retrieved, and including that JSON in your request, will update each property even though the value is the same. This can cause properties to appear to have been updated in auditing data when in fact they haven’t actually changed.


function UpdatAccount(AccountId,clientURL,AccountTobeUpdated)
{
 
var req = new XMLHttpRequest();
req.open('PATCH', clientURL + "/api/data/v8.0/accounts(" + AccountId + ")", true);
req.setRequestHeader("Content-type","application/json");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");

req.onreadystatechange = function () {
 if (this.readyState == 4 /* complete */) {
  req.onreadystatechange = null;
  if (this.status == 204) {   
   console.log("Updated account with ID: "+ AccountId)
  }
  else {
   var error = JSON.parse(this.response).error;
   console.log(error.message);
  }
 }
};
req.send(JSON.stringify(AccountTobeUpdated));
 

}

//This method will update an existing record.
function UpdateAccountUsingWebAPI() {

debugger;
var clientURL = Xrm.Page.context.getClientUrl();
var AccountId =  "B3A2B300-A8AF-E511-80DD-6C3BE5A878BC";

var AccountTobeUpdated ={};
AccountTobeUpdated["name"] ="My first Update On Account by API";
AccountTobeUpdated["accountnumber"] = "841843";
AccountTobeUpdated["fax"] ="9738310781";


UpdatAccount(AccountId,clientURL,AccountTobeUpdated)


}

No comments:

Post a Comment