On a recent project, I was given an interesting challenge by a customer using SharePoint. Basically the desire was to have a recursive "For loop" function in SharePoint using nothing but native tools (i.e. workflows). Googling the subject, I found very little helpful information, but I was able to come up with a workable solution of my own and thought it was worth blogging about.
The desired scenario was to have a bunch of records in a list where a user could perform a process on all of them (i.e. Approve drafts waiting for approval). In order to start this, the user would just use an action button on a form that would approve all of the records. This is easy to do in most programming languages, but without for loops in SharePoint, I had to rely on an "On Modify" workflow to solve my problem.
The crux of this solution is twofold. Firstly, each record needs to have a "State" variable assigned to it. This can be as simple as a text column with the value "Unapproved", "Approving", or "Approved". The second piece of the puzzle is the use of "On Modify" workflows. For the conditions of these workflows, the test and modifications need to be done on a lookup item from list, NOT current item. The architecture is best explained in the steps below:
- Action workflow updates 1 record state column from "Unapproved" to "Approving"
- On Modify workflow is triggered by previous step. It checks if there are any records in the "Approving" state (if not it terminates). If so it checks if there are any records still in the "Unapproved" state. If so, it goes to step 3, if not it skips to step 5.
- The On Modify workflow updates the next "Unapproved" record to "Approving"
- This triggers another "On Modify" workflow, returning to step 2
- Once there are no records left in "Unapproved" but records in the "Approving" state, the workflow updates the state column in the first "Approving" record it finds to be "Approved"
- This change triggers another On Modify workflow that then checks if there are more records in the "Approving" state, and if so returns to step 5.
- Once there are no "Approving" records left, all of the records should have been successfully moved from "Unapproved" to "Approved".
This example then creates a For Loop in SharePoint workflows, requiring the user to only press 1 "Approve All" button!
Learn more about DMC's SharePoint workflow services.