Execute the workflow from JScript In CRM
Hi,
We can run the CRM workflows from JScript, if we know the GUID of the workflow. Below are the execution steps.
Steps :-
- Get the GUID of workflow from name using OData Service (i.e., Using GetWorkflowIDByName(wfName) function )
- Execute the Workflow using the GUID (i.e., Using TriggerWorkflow(workflowGuid) function)
Below are the JScript functions mentioned in above steps.
function GetWorkflowIDByName(wfName) {
var serverUrl = Xrm.Page.context.getServerUrl();
//Prepare ODATA query to fetch WF GUID by WF Name
var odataSelect = serverUrl + “/xrmservices/2011/OrganizationData.svc/WorkflowSet?$select=WorkflowId&$filter=ActiveWorkflowId/Id ne null and Name eq ‘” + wfName + “‘”;
$.ajax({
type:“GET”,
contentType:“application/json; charset=utf-8”,
datatype:“json”,
url: odataSelect,
beforeSend:function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader(“Accept”, “application/json”); },
success:function(data, textStatus, XmlHttpRequest) {
RetrieveWorkflow(data.d);
},
error:function (XmlHttpRequest, textStatus, errorThrown) { alert(‘OData Select Failed: ‘+ odataSelect); }
});
}
function RetrieveWorkflow(Entity) {
var objFilteredWF = null;
objFilteredWF = Entity;
wfID =null;
//Get the WF GUID from OData result set
if (objFilteredWF != null && objFilteredWF.results != null && objFilteredWF.results.length != 0 && objFilteredWF.results[0].WorkflowId != null) {
wfID = objFilteredWF.results[0].WorkflowId;
TriggerWorkflow(wfID);
}
}
//Trigger WF using WorkflowGUID
function TriggerWorkflow(workflowGuid) {
try{
var soapBody = “<soap:Body>”+” <Execute xmlns=’http://schemas.microsoft.com/crm/2007/WebServices’>”
+ ” <Request xsi:type=\’ExecuteWorkflowRequest\’>”
+” <EntityId>” + Xrm.Page.data.entity.getId() + “</EntityId>”
+” <WorkflowId>” + workflowGuid + “</WorkflowId>”
+” </Request>”
+” </Execute>”
+“</soap:Body>”;
/*Wrap the Soap Body in a soap:Envelope.*/
var soapXml = “<soap:Envelope “
+” xmlns:soap=’http://schemas.xmlsoap.org/soap/envelope/’ “
+” xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’ “
+” xmlns:xsd=’http://www.w3.org/2001/XMLSchema’>”
+ GenerateAuthenticationHeader()
+soapBody +
“</soap:Envelope>”;
/* Create the XMLHTTP object for the execute method.*/
var xmlhttp = new ActiveXObject(“Msxml2.XMLHTTP”);
xmlhttp.open(“POST”, “/MSCRMservices/2007/crmservice.asmx”, false);
xmlhttp.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);
xmlhttp.setRequestHeader(“SOAPAction”, http://schemas.microsoft.com/crm/2007/WebServices/Execute);
/* Send the XMLHTTP object. */
xmlhttp.send(soapXml);
}
catch(e) {
}
}
🙂
Thank you. It worked fine for me.