Delete Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to delete 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 delete       
*/
function deleteRecord(entityPlurarName, id) {
    id = id.replace('{', '').replace('}', '');
    var IsDeleted = false;
    var serverURL = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest();
    req.open("DELETE", serverURL + "/api/data/v8.2/" + entityPlurarName + "(" + id + ")", false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.send();
    if (req.readyState == 4 /* complete */) {
        if (req.status == 204) {
            IsDeleted = true;
        }
        else {
            var error = JSON.parse(req.response).error;
            Xrm.Utility.alertDialog(error.message);
        }
    }
    return IsDeleted;
}
You can call the delete record method as:
var id=Xrm.Page.data.entity.getId();
alert(deleteRecord("accounts", id));

No comments:

Post a Comment