0

I have a function to start a workflow on multiple checked list items. It successfully identifies which items are selected and successfully starts the workflow, however it is only doing it on the last selected item.

The for loop starts the workflow multiple times on the last item rather than once on each item.

Could somebody please tell me what I'm doing wrong?

function startWorkflow() {
            var subID = "A2075514-B351-4A63-8511-626A2519AAD4";

            var context = SP.ClientContext.get_current();
            var web = context.get_web();
            var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
            var wfServiceManager = SP.WorkflowServices.WorkflowServicesManager.newObject(context, web);
            var subscription = wfServiceManager.getWorkflowSubscriptionService().getSubscription(subID);

            for (item in selectedItems)
            {
                var itemId = selectedItems[item].id;
                console.log(itemId);

                context.load(subscription);                     

                context.executeQueryAsync(
                    function(sender, args){
                        console.log("Subscription load success. Attempting to start workflow on " + itemId + ".");        
                        var inputParameters = {};

                        wfServiceManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemId, inputParameters);

                        context.executeQueryAsync(
                            function(sender, args){ console.log("Successfully starting workflow on " + itemId + "."); },
                            function(sender, args){ 
                                console.log("Failed to start workflow.");
                                console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());
                            }
                        );
                    },
                    function(sender,args){
                        console.log("Failed to load subscription.");
                        console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());
                    }
                );
            }
        }

2 Answers 2

0

Approached the situation differently.

  1. Used JavaScript to update a field in the list item. Code example here
  2. Made the workflow run on item change (where field = the comment I appended in step 1).
0

I think you may be running into a race condition.

Try loading your subscription before the for loop.

Run your for loop in the success callback of your first executeQueryAsync().

This way, it's not constantly instantiating a fresh instance of subscription for each item.

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.