How to call/launch/execute workflow and wait until its execution to make some action with JavaScript in Microsoft Dynamics CRM
Author of code for workflow executing is Jian Wang. I wrote a code that waits for the workflow to be completed.
So the code:
ExecuteWorkflow = function(entityId, workflowId)
{
var xml = "" +
"\"1.0\" encoding=\"utf-8\"?>" +
"\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" " +
" \"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" \"ExecuteWorkflowRequest\">" +
" " + entityId + "" +
" " + workflowId + "" +
" " +
" " +
" " +
" " +
"";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
return(resultXml.selectSingleNode('//soap:Envelope/soap:Body/ExecuteResponse/Response/Id').nodeTypedValue);
}
WaitWorkflowExecution = function(workflowId)
{
var xml = ""+
"+
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
GenerateAuthenticationHeader() +
"" +
"" +
"asyncoperation "+
"" +workflowId+""+
"" +
"" +
"statuscode "+
""+
""+
""+
""+
" ";
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
var resultXml = xHReq.responseXML;
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
setTimeout("WaitWorkflowExecution('" + workflowId + "');", 1000);
}
else
{
var executionstatus = resultXml.selectSingleNode("//soap:Envelope/soap:Body/RetrieveResponse/RetrieveResult/q1:statuscode").nodeTypedValue;
if (executionstatus == 30)//Workflow completed
{
alert("Workflow Completed!");
}
else
{
setTimeout("WaitWorkflowExecution('" + workflowId + "');", 1000);
}
}
}
var theWorkflowId = "6eb47269-4139-40b3-a96d-255ef2d78e6a"; //change to your workflow Id
var workflowInstanceId = ExecuteWorkflow(crmForm.ObjectId, theWorkflowId);
WaitWorkflowExecution(workflowInstanceId);
