Home > Customization, JavaScript, Microsoft Dynamics 365 > Execute Workflow using Web API in Dynamics 365

Execute Workflow using Web API in Dynamics 365

The following JavaScript code will be used to execute workflows in Dynamics 365.
Note: The following code will work only for Dynamics CRM 2016 Update 1 (8.1) and later releases including Dynamics 365.

function ExecuteWorkflow() {           
    var correspodenceId = Xrm.Page.data.entity.getId(); // case guid
    var workflowId = "{2e7dca90-3a40-1234-3456-a8e3fc1edcd2}"; //Replace your workflow id here. workflowId is fixed because of solution transfer and it is not going to change with environment.
    var functionName = "ExecuteWorkflow: "; //function name
    var query = "";
    try {
        //Define the query to execute the worklfow
        query = "workflows(" + workflowId.replace("}", "").replace("{", "") + ")/Microsoft.Dynamics.CRM.ExecuteWorkflow";
        var data = {
            "EntityId": correspodenceId
        };
        //Create a request                
        var req = new XMLHttpRequest();
        req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/" + query, 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 /* complete */) {
                req.onreadystatechange = null;

                if (this.status == 200) {
                    //success callback this returns null since no return value available.
                    var result = JSON.parse(this.response);


                } else {
                    //error callback
                    var error = JSON.parse(this.response).error;
                }
            }
        };
        req.send(JSON.stringify(data));
    } catch (e) {
        alert('An error has occurred - Function name:' + functionName + 'Error:' + e) //throw exception                        
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: