Calling a Dynamics 365 Workflow through JavaScript

7 Comments

In Dynamics 365, you may want to call a workflow directly from JavaScript. This can be achieved using the WebAPI.

Let’s say we have a workflow as follows, that creates a task on the account:

For the sake of the demo, we will hardcode the Workflow Id and Account Id.

Copy the Workflow Id from the URL:

Now create an account:

Get the Id of the account:

Now the code. Note we are calling Microsoft.Dynamics.CRM.ExecuteWorkflow:

var entity = {
   "EntityId": "D82A5713-3C39-E811-A952-000D3A36478D" // accountId
};

var WorkflowId = "4E79CE7A-BB73-409D-9F6A-7FCBB49FFD94";

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/workflows(" + WorkflowId + ")/Microsoft.Dynamics.CRM.ExecuteWorkflow", true);
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) {
            Xrm.Utility.alertDialog("Success");
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));

Running this, we get:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

7 Responses to Calling a Dynamics 365 Workflow through JavaScript

  1. With the deprecation of Xrm.Page looming you can switch that to use the following to get the client url:
    var globalContext = Xrm.Utility.getGlobalContext();
    var clientUrl = globalContext.getClientUrl();
    Note: Combining those into a one liner for some reason doesn’t work (or didn’t for me).

    Also instead of Alerts the new Xrm.Utility.showProgressIndicator(message) method feels like a better UX, then just closeProgressIndicator on success (and error for completeness).

Leave a Reply

Your email address will not be published. Required fields are marked *