Search This Blog

Saturday, January 14, 2023

DYNAMICS 365 CALL WORKFLOW FROM JAVASCRIPT AND C#

 I will show you how to call workflows from JavaScript or C# and to accomplish this, you need two parameters:

  • The Workflow Id that you want to call AND
  • The Record Id that the workflow will be executed against
For the sake of the demo, I created a workflow that will set the Account Name field to:
  • WF Called and Updated From JavaScript after calling the workflow from JavaScript
  • WF Called and Updated From C# after calling the workflow from C#
Below is the end result after calling the workflow in JavaScript
Call workflow in JavaScript

Below is the end result after calling the workflow in C#
Call workflow in C#

The below function can be used to call the workflow in JavaScript

function executeWorkflow(context, workflowId, recordId) {
var formContext = context.getFormContext();
var data = {
"EntityId": recordId
};
var WorkflowId = workflowId;
var req = new XMLHttpRequest();
req.open("POST", formContext.context.getClientUrl() + "/api/data/v9.1/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 || this.status === 204) { // Asynchronous || Synchronous
Xrm.Utility.alertDialog("Success");
}
else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send(JSON.stringify(data));
}

The below function can be used to call the workflow in C#

public void ExecuteWorkflow(Guid workflowGuid, Guid recordGuid)
{
try
{
var executeWorkflowRequest = new ExecuteWorkflowRequest()
{
WorkflowId = workflowGuid, // Guid of workflow
EntityId = recordGuid // Guid of record
};
var executeWorkflowResponse = (ExecuteWorkflowResponse)AdminService.Execute(executeWorkflowRequest);
}
catch (InvalidPluginExecutionException ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}

Bonus Tips:
  • The workflow must be saved to run on-demand
  • The workflow can be saved to run as Synchronous or Asynchronous

No comments:

Post a Comment