Call Workflow from Javascript

This is the code needed.


function triggerBulkWorkflowByName(wfName, svid) {
    var wId = getWorkflowId(wfName);
    triggerWorkflow(wId, svid);
}

function getWorkflowId(wfName) {

    var urlPos = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/WorkflowSet?$filter=Name eq '" + wfName + "' and ParentWorkflowId/Id eq null";
    //var urlPos = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/WorkflowSet";

    var id;

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        async: false,
        datatype: "json",
        url: urlPos,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (data.d.results.length > 0) {
                id = data.d.results[0].WorkflowId;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Error");

        }
    });

    return id;
}

function triggerWorkflow(wfId, entityId) {

    try {
var soapBody = "<soap:Body>" + 
" <Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
 " <Request xsi:type=\'ExecuteWorkflowRequest\'>" +
 " <EntityId>" + entityId + "</EntityId>" +
 " <WorkflowId>" + wfId + "</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) {
        alert("An error has occured: " + e.description);
    }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s