Monday, April 16, 2012

Executing CRM 2011 workflow via Javascript

To execute a workflow we have to use the soap web service. We cannot use oData service. So we have to create a soap envelope and post it to the organization web service. The following function will execute the workflow.
function ExecuteWorkFlow(entityId,workflowId,url)
{

    var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
    url = url + OrgServicePath;
    var request;
    request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
  "<s:Body>" +
    "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"+
      "<request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">"+
        "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">"+
          "<a:KeyValuePairOfstringanyType>"+
            "<c:key>EntityId</c:key>"+
            "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">"+ entityId+"</c:value>"+
          "</a:KeyValuePairOfstringanyType>"+
          "<a:KeyValuePairOfstringanyType>"+
            "<c:key>WorkflowId</c:key>"+
            "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">"+ workflowId +"</c:value>"+
          "</a:KeyValuePairOfstringanyType>"+
        "</a:Parameters>"+
        "<a:RequestId i:nil=\"true\" />"+
        "<a:RequestName>ExecuteWorkflow</a:RequestName>"+
      "</request>"+
    "</Execute>"+
  "</s:Body>"+
"</s:Envelope>";

  var req = new XMLHttpRequest();
  req.open("POST", url, true)
  // Responses will return XML. It isn't possible to return JSON.
  req.setRequestHeader("Accept", "application/xml, text/xml, */*");
  req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
  req.onreadystatechange = function () { assignResponse(req); };
  req.send(request);
  

}

function assignResponse(req) {
if (req.readyState == 4) {
    if (req.status == 200) {
        alert('successfully executed the workflow');
   }
   }
}

Happying Coding!

1 comment:

  1. Hiya, I am really glad I have found this info. Nowadays bloggers publish only about gossip and net stuff and this is really annoying. A good website with exciting content, this is what I need. Thanks for making this web-site, and I will be visiting again. Do you do newsletters by email?
    startup internet company

    ReplyDelete