Featured Post

Web API Requests Series

Web API Series:  Create and Retrieve , Update and Delete , Retrieve Multiple , Associate/Disassociate , Impersonation , Run Workflows

Showing posts with label dynamics crm 365. Show all posts
Showing posts with label dynamics crm 365. Show all posts

03 February 2017

Run Workflows using CRM 365 Web Api

Hi all, Today I am going to post a sample code you can use to run a workflow in CRM 365 using the new Web Api.

The function takes three parameters in input: the workflow Guid, the record Guid and a boolean to tell the Web Api whether or not to run the workflow synchronously; true = asynchronously which is the default behaviour, false = synchronously.
The Workflow should be set up to be run either as a child or On demand Workflow otherwise you'll get an error.

var _runWorkflow = function (workflowId, recordId) {

        var parameters = {};
        parameters.EntityId = recordId;

        var req = new XMLHttpRequest();
        req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/workflows(" + workflowId + ")/Microsoft.Dynamics.CRM.ExecuteWorkflow", 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 === 200) {
                    var results = JSON.parse(this.response);
                } else {
                    //Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send(JSON.stringify(parameters));
    }

Here is an example of how to call the function above after saving the record via javascript:

Xrm.Page.data.save().then(
            function () {
                var entityType = Xrm.Page.data.entity.getEntityName();
                var recordId = Xrm.Page.data.entity.getId();

                var wfGuid = LDA.Functions.Common.GetWorkflowGuid(entityType);

                if (wfGuid == "na") return;

                LDA.Functions.Common.RunWorkflow(wfGuid, recordId.replace("}", "").replace("{", ""));
             
                Xrm.Page.data.refresh(false);
            },
            function () {
                //handle errors
            }
        );



That was it, very simple and straight forward, hope it helps to get you started with the new CRM 365 Web Api. If you have any questions leave a comment and I'll get back to you ASAP.