0

I'm not super familiar with javascript and how it interacts with SharePoint, but I was tasked with starting a workflow on several items with one click. I did some research and found this which walked me through everything step by step.

I ended up with this code and have added the two jquery files into the SharePoint site.

<script type="text/javascript" src="...JS/StartWorkflow/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="...JS/StartWorkflow/jquery.SPServices-2014.02.min.js"></script>

<script type="text/javascript">
function StartWFOnSelectedItems()
{
    var listName = "NewArrivalInformation";
    var ctx = SP.ClientContext.get_current();
    var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
    var url = document.URL;
    var item;
    for (item in selectedItems)
    {
        var itemId = selectedItems[item].id;
        url = url.split(listName)[0];
        url = url+listName+'/'+itemId+'_.000';
        StartWorkflow(url,itemId);
    // alert("Workflow initiated");
    }
    alert("Workflow started on selected items");
}


function StartWorkflow(ItemURL,ItemID)
 {
    $().SPServices({
        operation: "StartWorkflow",
        item: ItemURL,
        templateId: "{6eb308a5-46e3-4673-8b20-e3c7c1d37658}",
        workflowParameters: "<root />",
        completefunc: function() 
        {
            alert(ItemID);      
        }
    });
}
</script>

Obviously, I usually have the full links at the top, but I've taken the first part of it out for privacy reasons. I believe I linked everything in my site correctly, because when I click the button I've added, I get the alerts listed within the script and within both of the functions, meaning they're being triggered. However, the workflow doesn't run. I have checked multiple times that the template ID is correct, and I'm at a loss as to where this could be going wrong. The workflow runs when I trigger it the normal way (through the workflows button), but running it using this script does not work.

2 Answers 2

0

You could try this:

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="/_layouts/15/sp.workflowservices.js"></script>
<script src="/_layouts/15/SP.Runtime.js"></script>
<script>
  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', init);
  function init() {
    $.getScript(SP.Utilities.Utility.getLayoutsPageUrl('sp.js'), function () {
      $.getScript(SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'), function () {
        StartWorkflow("workflow subscription id","","site url");
      });
    });
  }
  //dialog element to show during processing
  var dlg = null;
  //Subscription id – Workflow subscription id
  //list item id for which to start workflow. If site workflow, then send null for itemId
  //SiteURL – site collection where the workflow exists
  function StartWorkflow(subscriptionId, itemId, SiteURL) {
    showInProgressDialog();
    var ctx = new SP.ClientContext(SiteURL);
    var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
    var subscription = wfManager.getWorkflowSubscriptionService().getSubscription(subscriptionId);
    ctx.load(subscription, 'PropertyDefinitions');
    ctx.executeQueryAsync(
      function (sender, args) {
        var params = new Object();
        //Find initiation data to be passed to workflow.
        var formData = subscription.get_propertyDefinitions()["FormData"];
        if (formData != null &&   formData != 'undefined' &&   formData != "") {
      var assocParams = formData.split(";#");
      for (var i = 0; i < assocParams.length; i++) {
        params[assocParams[i]] = subscription.get_propertyDefinitions()[assocParams[i]];
      }
    }
    if (itemId) {
      wfManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemId, params);
    }
    else {
      wfManager.getWorkflowInstanceService().startWorkflow(subscription, params);
    }
    ctx.executeQueryAsync(
      function (sender, args) {
        closeInProgressDialog(SiteURL);
      },
      function (sender, args) {
        closeInProgressDialog(SiteURL);
        $('#msg')[0].innerHTML = "Woops – something went wrong, the document may have already been reviewed";
      }
    );
  },
  function (sender, args) {
    closeInProgressDialog(SiteURL);
    $('#msg')[0].innerHTML = "Woops – something went wrong, the document may have already been reviewed";
  }
);
}

  function closeInProgressDialog(SiteURL) {
    if (dlg != null) {
      dlg.close();
      $('#msg')[0].innerHTML = "Thank you – you can now close the page";
    }
  }
  function showInProgressDialog() {
    if (dlg == null) {
      dlg = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait…", "Waiting for workflow…", null, null);
    }
  }
</script>

Source:https://spdeveloper.co.uk/blog/2018/09/01/starting-a-sharepoint-workflow-via-javascript/

0

If you're OK with using a different third party library, you could use my lib called SharepointPlus, then you can replace the use of JQuery and SPServices.

I'll assume you're using "Sharepoint 2010" for the workflow platform type (the most reliable ones) – see the documentation.
It's also possible to use a "Sharepoint 2013" for the workflow platform type (see the documentation). screenshot of the platform type selection for workflows

A couple of requirements:

  1. Your workflow needs to have the option to be manually started
    screenshot of the option "Allow this workflow to be manually started"
  2. The current user needs to have enough rights to trigger the workflow

Then the code will look like that:

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus/browser/sharepointplus.js"></script>
<script>
function StartWFOnSelectedItems() {
  var ctx = SP.ClientContext.get_current();
  var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
  for (var item in selectedItems) {
    // I'll suppose "selectedItems[item].id" is the item ID
    var itemID = selectedItems[item].id;
    $SP().list("NewArrivalInformation").startWorkflow({
      ID:itemID,
      workflowName:"Name of the workflow to start"
    })
    .then(function() {
      console.log("Workflow completed for "+itemID);
    })
    .catch(function() {
      console.error("Workflow failed for "+itemID);
    })
  }
}
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.