Calling entity based Action 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 JavaScript code to call an entity based Action using Web API in Dynamics CRM.
/*
actionName: Name of action
entityPlurarName: entityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
entityId: guid of record going to update
param: param is an object that contians the parameter needed to be passed to the calling action.
e.g
var param = {
    param1: "this is string parameter",
    param2: false,// boolean
};  
*/
 function callEntityBasedAction(actionName, entityPlurarName, entityId, param) {
    var serverURL = Xrm.Page.context.getClientUrl();
    entityId = entityId.replace('{', '').replace('}', '');
    var result = null;
    var req = new XMLHttpRequest();
    req.open("POST", serverURL + "/api/data/v8.0/"+ entityPlurarName + "(" + entityId + ")/Microsoft.Dynamics.CRM." + actionName, 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.onreadystatechange = function () {
        if (this.readyState == 4) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                result = JSON.parse(this.response);
            } else if (this.status == 204) {
                console.log("Request executed successfully without a response");
            } else {
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };
    if (param) {
        req.send(window.JSON.stringify(param));
    } else {
        req.send();
    }
    return result;
}

No comments:

Post a Comment