Monday 20 March 2017

How to call a plugin from a JavaScript or a ribbon button?


Sometimes there are situations where you need to call a plugin from a JavaScript or click of a ribbon button. With the help of actions and latest web API this is easily achievable.

Step 1

Under Processes create a new Process with Category selected as Action; give a name and select the entity. In this example I have selected Account as the entity. It’s just a blank action with no arguments or steps.



Step 2

Create your plugin and register your plugin on that action you created. Make sure you have activated your action and published. Otherwise you will not see the newly created action in the plugin registration tool. If you still don’t see your action name in messages in plugin registration tool close the plugin registration tool and open again. It should resolve this.



Step 3

In your JavaScript on account form use following code; replace the action name with the unique name of your action.
In this example replace new_AccountAction with your unique name.
function CallAction() {   
    var currentRecordIdString = Xrm.Page.data.entity.getId();
    var currentRecordId = currentRecordIdString.replace("{", '').replace("}", '');
    var query = "accounts(" + currentRecordId + ")/Microsoft.Dynamics.CRM.new_AccountAction";
    var req = new XMLHttpRequest();
    var url = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/" + query;
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/" + query, 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.onreadystatechange = function () {
        if (this.readyState == 4) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                //Xrm.Utility.alertDialog("Action Called");
            }
            else {
                var error = JSON.parse(this.response).error;
                Xrm.Utility.alertDialog(error.message);
            }
        }
    };
    req.send();
}


That’s all. Then you can call this function from your ribbon button if you need to.



No comments:

Post a Comment

How to tackle Concurrent Business Process flows

Dynamics 365 has introduced the new feature of Concurrent Business Process Flows. Here is a couple of good articles on that: http://dev...