Associate 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 Associate 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 associateRequest(currentEntityPlurarName, currentEntityId, relationShipName, otherEntityPlurarName, otherEntityId) {
    var serverURL = Xrm.Page.context.getClientUrl();
    var associate = {}
    associate["@odata.id"] = serverURL + "/api/data/v8.2/" + otherEntityPlurarName + "(" + otherEntityId + ")"
    
    var req = new XMLHttpRequest();
    req.open("POST", serverURL + "/api/data/v8.2/" + currentEntityPlurarName + "(" + currentEntityId + ")/" + relationShipName + "/$ref", 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 Associated');
            } else {
                var error = JSON.parse(this.response).error;
                Xrm.Utility.alertDialog(error.message);
            }
        }
    };
    req.send(JSON.stringify(associate));
}
You can call the associate 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);
associateRequest(currentEntityName, currentEntityId, relationShipName, otherEntityName, otherEntityId);

No comments:

Post a Comment