Update Record using Web API

Following is detail sample code to update a record using Web API in Dynamics CRM.
/*
entityPlurarName: entityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
id: guid of record going to update
entityObject: entityObject is an object that of entity contians fields and values that needed to be create.
e.g
  var entityObject = {};
      entityObject["originatingleadid@odata.bind"] = "/leads(" + guid + ")";  // lookup    
      contact["firstname"] = string value;  // Single line of text 
      contact["po_preferredlanguage"] = string value; //Option set
      contact["donotemail"] = true/false //two Option
*/
function updateRecord(entityPlurarName, id, entityObject) {
    var IsUpdated = false;
    var req = new XMLHttpRequest();
    req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityPlurarName + "(" + id + ")", false);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.send(JSON.stringify(entityObject));
    if (req.readyState === 4) {
        if (req.status === 204) {
            IsUpdated = true;
        }
        else {
            var error = JSON.parse(req.response).error;
            Xrm.Utility.alertDialog(error.message);
        }
    }
    return IsUpdated;
}
You can call the update record method as:
var account = {};
account["name"] = "Test Account name 2";  // Single line of text 
account["paymenttermscode"] = "4";//Text(Net 30) //Option set
account["creditonhold"] = false; //two Option 
alert(updateRecord("accounts", removeCurlyBraces(Xrm.Page.data.entity.getId()), account));

No comments:

Post a Comment