How to Start SharePoint 2013 Workflows on Selected Items

This article first appeared as an email response to one of our clients. He described a very common use case where you have two libraries of documents, the first library is where the users work with draft documents and the other library stores the final versions of documents. In this case, users want to be able to select finished documents and move it in one click. The obvious solution for this is to use a workflow that will move documents to the final Document Library. But there is one question, how to start the workflow on the selected list items? When I was thinking about the answer to that question, I realized that it is not as trivial as it seems, because a list level workflow can be begun only on a single document. How to start multiple workflows on selected documents? In the article, I will describe how to implement such a solution.

I divided this article into the following three main parts:

  • Get selected items via JavaScript
  • Start SharePoint 2013 workflow from JavaScript
  • Add a custom button to the list ribbon

Before we start, I want to show what the result will be. In the figure below you can see the custom button on the ribbon that will launch a workflows on selected documents.



Figure 1: Ribbon New Button

How to get selected elements via JavaScript

First I will describe how to get selected list items from a SharePoint list. To do this, you can use the special JavaScript function getSelectedItems. Please see the example below:

  1. var ctx = SP.ClientContext.get_current();var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);  
  2. for (item in selectedItems)  
  3. {  
  4. var itemId = selectedItems[item].id;  
  5. console.log(itemId);  
  6. }  

As a result of execution, this snippet of code shows the IDs of selected list items in the console log.

How to start workflow

Since SharePoint 2013, Microsoft has added a new workflow engine. The new JavaScript API for manipulation of workflows also became available. In this article, I will not describe it, but if you are interested, you can find more information from the Andrei Markeev's article. I will show you a ready-to-use JavaScript snippet that can run a workflow on a single list item.

  1. function startWorkflow(itemID, subID)
    var context = SP.ClientContext.get_current(); var web = context.get_web();  
  2.    var wfServiceManager = SP.WorkflowServices.WorkflowServicesManager.newObject(context, web);  
  3.    var subscription = wfServiceManager.getWorkflowSubscriptionService().getSubscription(subID);  
  4.   
  5.    context.load(subscription);  
  6.    context.executeQueryAsync(  
  7.    function(sender, args){  
  8.       console.log("Subscription load success. Attempting to start workflow.");  
  9.       var inputParameters = {};  
  10.       wfServiceManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemID, inputParameters);  
  11.   
  12.       context.executeQueryAsync(  
  13.       function(sender, args){ console.log("Successfully starting workflow."); },  
  14.       function(sender, args){  
  15.       console.log("Failed to start workflow.");  
  16.          console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());  
  17.       }  
  18.    );  
  19.    },  
  20.    function(sender,args){  
  21.       console.log("Failed to load subscription.");  
  22.       console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());  
  23.       }  
  24.    );  
  25. }  

This simple JavaScript function launches a workflow on a list item. The workflow subscription is specified by SubID argument. To identify the subscription ID of your workflow you can navigate to the workflows start page and see the URL in your browser, it should look like this (the bold GUID is the workflow subscription ID): “javascript:StartWorkflow4('6eb43e78-6e6c-486a-9147-3e3870f3a44e', '19', '{FA41C64B-42CD-4A3F-A1AF-CF674AB35C57}')”.



Figure 2: Log Workflow Link

How to Add a Button to the SharePoint Ribbon

A very important part is how a user will interact with our system. I believe that the user experience is very important for any system. In our case our plan is for the user to select the documents and click on the ribbon button that will move them to another Document Library.

There are various ways to add a button on the ribbon, but in this article, I want to describe the simplest. We will use SharePoint Designer to do this. When we use SharePoint Designer we have some limitations, for example we cannot add a new ribbon tab or hide an existing button, but from another point of view if we need to just add a button to the ribbon then it will take five minutes of our time and it doesn't require programming skills.

Please open the SharePoint Designer, navigate to “List and Libraries” and choose your Document Library.



Figure 3: SharePoint Designer Open Document Libraries

To add a ribbon button please click inside the “Custom Actions” area and choose in the ribbon “Custom Actions” - “View Ribbon”.



Figure 4: SharePoint Designer Open Document Libraries Custom Actions

When you fill in all the fields, you should see something like on the figure below in your list.



Figure 5: Ribbon CustomAction Filled

Please pay attention to the property “Navigate URL”, I filled it with the following text:

  1. javascript:PlumsailDemo.WFPack.API.StartListWorkflowOnSelectedItems("{6eb43e78-6e6c-486a-9147-3e3870f3a44e}");  

This is a call of our function with the argument “Subscription ID” of our workflow.

Join all of it together

OK, we almost did it. All we need to do is to combine and place the JavaScript in SharePoint. To add our JavaScript on the page we will use the ScriptEditor Web part. To do this you need to enter into edit page mode. Click on “Add a Web Part” and select “Script Editor” in the “Media and Content” group.



Figure 6: Script Editor WebPart

I changed the JavaScript file a little bit to simplify using:

  1. < script type = "text/javascript" > // <![CDATA[var PlumsailDemo = PlumsailDemo || {}; PlumsailDemo.WFPack = PlumsailDemo.WFPack || {};  
  2.   
  3. PlumsailDemo.WFPack.API = (function() {  
  4.     var self = this;  
  5.     self.Context = null,  
  6.     self.WFManager = null;  
  7.   
  8.     SP.SOD.executeFunc("sp.js""SP.ClientContext"function() {  
  9.         SP.SOD.registerSod('sp.workflowservices.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'));  
  10.         SP.SOD.executeFunc('sp.workflowservices.js'"SP.WorkflowServices.WorkflowServicesManager",  
  11.   
  12.         function() {  
  13.             self.Context = SP.ClientContext.get_current();  
  14.             var web = self.Context.get_web();  
  15.             self.WFManager = SP.WorkflowServices.WorkflowServicesManager.newObject(self.Context, web);  
  16.         });  
  17.     });  
  18.   
  19.     StartListWorkflowOnSelectedItems = function(subID) {  
  20.         var selectedItems = SP.ListOperation.Selection.getSelectedItems(self.Context);  
  21.   
  22.         for (item in selectedItems) {  
  23.             var itemId = selectedItems[item].id;  
  24.             self.StartListWorkflow(itemId, subID);  
  25.         }  
  26.     };  
  27.   
  28.     StartListWorkflow = function(itemID, subID) {  
  29.         var subscription = self.WFManager.getWorkflowSubscriptionService().getSubscription(subID);  
  30.   
  31.         self.Context.load(subscription);  
  32.         self.Context.executeQueryAsync(  
  33.   
  34.         function(sender, args) {  
  35.             var inputParameters = {};  
  36.   
  37.             self.WFManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemID, inputParameters);  
  38.   
  39.             self.Context.executeQueryAsync(  
  40.   
  41.             function(sender, args) {  
  42.                 var message = "The workflow " + subscription.get_name() + " was started on item with ID " + itemID;  
  43.                 SP.UI.Notify.addNotification(message, false);  
  44.             },  
  45.   
  46.             function(sender, args) {  
  47.                 var message = "Failed to start workflow " + subscription.get_name() + " on item with ID " + itemID;  
  48.                 SP.UI.Notify.addNotification(message, false);  
  49.                 console.log("Failed to start workflow.");  
  50.                 console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());  
  51.             });  
  52.         },  
  53.   
  54.         function(sender, args) {  
  55.             var message = "Failed to load subscription " + subID;  
  56.             SP.UI.Notify.addNotification(message, false);  
  57.             console.log("Failed to load subscription.");  
  58.             console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());  
  59.         });  
  60.   
  61.     };  
  62.   
  63.     return {  
  64.         StartListWorkflow: StartListWorkflow,  
  65.         StartListWorkflowOnSelectedItems: StartListWorkflowOnSelectedItems  
  66.     };  
  67. })();  
  68. // ]]></script> 

Conclusion

In this article, we reviewed how to start multiple workflows on the selected list items. In conclusion, I want to mention about one little detail, in such approach it is very difficult to monitor the status and errors of the workflows because it works on multiple list items. But you can extend my simple JavaScript with some workflow tracking logic if you have enough JavaScript/SharePoint skills.

You need to understand what will be the load for the system. For small systems this is an acceptable approach, but for highly loaded systems this is not so good. You can consider other approaches for moving documents, like a single-site level workflow or a custom coded solution.

As an alternative to this approach, you can start a site-level workflow and pass to it the selected IDs, but this is a theme for another article.

Please feel free to comment, I will be happy to answer to your questions.