Thursday, 10 August 2017

Find Workflow Guid and trigger it from JavaScript


In MS Dynamics CRM we can trigger the workflow by various ways. Sometimes there is requirement to run a on-demand workflow from a JavaScript file or you say on click of a button from page.
As we know we can call a JavaScript file on a button click and then using below code can trigger the workflow.

function triggerWFfrom JS()
{
       Var recordId = Xrm.Page.data.entity.getId();       Process.callWorkflow("CBAB0F54-847D-5EEA-9FDB-GH3564", //Guid of the WF

            recordId ,//entity id on which the workflow will be triggered
            function () {alert("Workflow executed successfully");},//callback for successful WF execution
            function () {alert("Error in workflow execution");}//callback for failed workflow execution

      );
 }

we use Process JS object and function named callWorkflow() to call workflow execution. Behind the curtain, Process.js is library publicly available, and works as a wrapper which prepares XML payload and request for workflow execution. Internally it also uses Organization web service. 
You can download it from this URL: 
https://processjs.codeplex.com/

But if we are using hard-coded workflow id then after every deployment we need to change the workflow id. we know in every environment the GUID of workflow may be different. So to avoid this situation and pain we can use the below code to find the workflow id with workflow name(same parameter in every environment) and use this id to trigger the workflow.

function GetWorkflowId(wfName)
{
    var serverUrl = Xrm.Page.context.getClientUrl();
   //Odata query to fetch the WF Guid by WF name
    var odataQuery = serverUrl + '/XRMServices/2011/OrganizationData.svc /WorkflowSet?$select=WorkflowId&$filter=StateCode/Value eq 1 and ParentWorkflowId/Id eq null and Name eq \'' + wfName + '\'';
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", odataQuery, false);
    xmlHttp.send();
     if (xmlHttp.status == 200) {
          var result = xmlHttp.responseText;
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML(result);

        return xmlDoc.getElementsByTagName("d:WorkflowId")[0].childNodes[0].nodeValue;
     }
}

And now the code to trigger the workflow will be:

function triggerWFfrom JS()
{
       Var recordId = Xrm.Page.data.entity.getId();

        Var wfId = GetWorkflowId("On-demand WF name");

         Process.callWorkflow(wfId, //Guid of the WF

            recordId ,//entity id on which the workflow will be triggered
            function () {alert("Workflow executed successfully");},//callback for successful WF execution
            function () {alert("Error in workflow execution");}//callback for failed workflow execution

      );
 }

No comments:

Post a Comment

Have you ever faced an issue where you need to import some record without changing GUID of the record? For example if we need to migr...