Disassociate 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 disassociate a record using Web API in Dynamics CRM.
/*
currentEntityPlurarName: currentEntityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
currentEntityId: guid of current entity record
otherEntityPlurarName: otherEntityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
otherEntityId: guid of other entity record       
*/
function disAssociateRequest(currentEntityPlurarName, currentEntityId, relationShipName, otherEntityPlurarName, otherEntityId) {
    var serverURL = Xrm.Page.context.getClientUrl();
    var query = currentEntityPlurarName + "(" + currentEntityId + ")/" + relationShipName + "/$ref?$id=" + serverURL + "/api/data/v8.2/" + otherEntityPlurarName + "(" + otherEntityId + ")";
    var req = new XMLHttpRequest();
    req.open("DELETE", serverURL + "/api/data/v8.2/" + query, true);
    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.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                //alert('Record Disassociated');
            } else {
                var error = JSON.parse(this.response).error;
                Xrm.Utility.alertDialog(error.message);
            }
        }
    };
    req.send();
}
You can call the disassociate record method as:
    var currentEntityName = "accounts";
    var currentEntityId = removeCurlyBraces(Xrm.Page.data.entity.getId())
    var relationShipName = "new_account_contact";
    var otherEntityName = "contacts";
    var otherEntityId = removeCurlyBraces(Xrm.Page.getAttribute("primarycontactid").getValue()[0].id);
    disAssociateRequest(currentEntityName, currentEntityId, relationShipName, otherEntityName, otherEntityId);

No comments:

Post a Comment