Admins / Developers / Flow

Salesforce Flow Loops – Best Practices and Examples

By Tim Combridge

When you’re building a Salesforce flow, there are often times where you’ve got a collection of items and you want to perform a specific action or check an individual item. For example, let’s say you wanted to create a number of tasks related to a record when users made selections on a multi-picklist. Rather than layering the flow with multiple Decision elements (i.e., Did they select Option A, did they select Option B and so on) – this is where Loops would come in to simplify the flow processing.

If you’re looking for a way to perform a specific action more than once, Loops are going to be your best friend. In this article, we’ll dive into what Loops are, how to use them, and some best practices to keep in mind.

What is a Loop in Salesforce Flow?

A Loop is a Salesforce Flow element that is used to iterate through a number of items in a collection variable.

There are three main components of a Loop:

  • Collection Variable: This is the Collection you want to loop through – the Collection contains multiple Variables, each of which you want to either assess or action.
  • Loop Variable: This will be the temporary holding place of a single Variable from within the Collection as it is being processed. This can either be created manually or can be created automatically when setting up the Loop.
  • Direction: This allows you to choose whether you want to Loop from first to last, or last to first item in a Collection. In a lot of basic scenarios, this isn’t so critical.

How to Create and Use a Loop

Let’s use this scenario: An Account has an Active__c Checkbox field, as does the Contact object. Your manager has asked you to create a flow that marks all child contact records as Active or Inactive, based on the value of the account’s field. There are multiple ways to do this – one of which is to use a Loop to iterate through all the contact records and use an assignment to set the new value.

Note: There are definitely better ways to execute this example, but this example provides a very simple way to demonstrate the Loop feature, so we’re going with it!

If you’re following along at home, all you need to do is ensure there’s an Active__c Checkbox field on both the account and contact.

The first step is to create a new record-triggered flow that runs After Update. This will be triggered whenever an account record’s Active field is changed.

The next thing you need to do is collect all the relevant contact records into a Collection so that you can process them in a Loop. After the Start element, create a Get Records element as below:

Ensure that you’ve selected All Records under the How Many Records to Store header. This ensures that a Collection, rather than a single record variable, is captured.

Now that you have your Collection, it’s time to loop through the records and change the Active field, according to the account’s new value. To do this, create a Loop after the Get Records element. Use the Collection that was created in the Get Records element.

The next step is to assign the new value, using an assignment. (Best practice tip incoming!) Never perform a DML Statement within a Loop! We’ll talk more about this later.

You’re going to perform a ‘double assign’ – this is a nickname I’ve given to the method of assigning a Variable and then assigning it to a new Collection. 

The first assignment will be used to set the new Active value on the Contact Variable. Create your Assignment Variable within the Loop as follows:

The second assignment will be used to put the contact into a new Collection that you’ll later use to update all the contact records at once. Firstly, you’ll need to create a new Contact Collection Variable as follows:

You now need to assign the contact record to the new Collection Variable. This is so that you have a single Collection Variable to update after the Loop has closed. This assignment needs to be created within the flow, but after the first assignment. Create your assignment as follows:

Finally, you need to create your Update at the end of your flow. This will commit the changes you’ve assigned and update the contact records. Create your Update element as follows:

That’s it! Your flow is complete. All you need to do now is test it (we won’t go into that in this article). Your completed flow should look something like this:

Best Practices When Using Loops in Salesforce Flow

While creating the above flow, we’ve already discussed some best practices that need to be taken into account while using Loops in Salesforce Flows. Let’s reiterate and go into further detail:

Never perform a DML statement inside of a Loop.

Avoid using the pink Data elements inside a Loop. There’s no better way to avoid hitting a governor limit than designing to avoid them!

In the flow above, you’re only pushing a single DML statement – the Update Contacts at the end of your flow. If you’d use the Update Contact element inside the Loop instead of using the double assign tactic, there’s no way to predict how many times it’ll be used. You may have an account with over a thousand contacts, which means the flow will attempt to use the Update call a thousand times – this will fail. If you assign a thousand records and use the Update call once (as you’ve done above), you won’t run into the same issue.

Assign to a new Collection rather than reusing the original one.

Reusing a variable is never a good idea, especially when working with Loops. It’s better to create a new Collection Variable and populate it with your updated records, for use later on in the flow (in the example above, updateContact was your new Collection Variable).

Summary and Further Learning

In the above example, you learned how to use Loops in a flow and also some key best practices to keep in mind, when using Loops. If you’d like to learn more about using Loops and using flows in general, there’s a few options I’d recommend.

Firstly, you have Trailhead. Trailhead is Salesforce’s free training platform that has multiple Flow-based modules, all of which you can study at your own pace.

One more source that I used quite a bit when learning about flows back in my early days was Rakesh Gupta’s AutomationChampion.com. There are a bunch of fantastic examples of flows that use Loops (like this one). They’re a little bit more complex than Trailhead, but offer a great next step for those who are looking to further their Flow education.

The Author

Tim Combridge

Tim is the Managing Director at Sensible Giraffe, passionately educating others via high-quality blog content and training courses including the Ultimate Salesforce Flow Foundation Course.

Comments:

    Mike F
    September 21, 2021 9:55 am
    Your completed flow graphic doesn’t follow what you wrote: “The first Assignment will be used to set the new Active value on the Contact Variable…The second Assignment will be used to put the Contact into a new Collection.” So which is correct? Does it matter? Seems to me you would indeed update the variable and add it to the collection to be updated all at once. Just like you wrote it. So how is the graphic wrong?
    Christine Marshall
    September 23, 2021 9:22 am
    Thank you for pointing out this error! We have now corrected it.
    John Sadler
    February 02, 2022 4:27 am
    I have an update Leads and Contacts flow to update a field based on the User being made inactive. Seems to work fine until there is a User who owns 1300 Contacts. Will work for 30+ leads and/or contacts. Is there a limit to the number of records that may be updated using Loop (I reduced the batch size to 10)? I'm not getting any Apex governor type errors, in fact, no errors at all. Worth noting, I only got this to work when I created a Scheduled path that ran 1 minute after the User was changed to Inactive
    John Sadler
    February 07, 2022 1:47 am
    Error: Number of iterations exceeded Looks like the sample Flow shown above could run into the same issue I have encountered and would possibly get a Number of iterations exceeded error. This is the error I got when I ran a debug. There were 1300 contacts but Salesforce treats this more like 3900 and the limit is 2000. I now have to figure out how to run the Flow in batches
    Harshala Godse
    April 21, 2022 5:56 pm
    If your flow is an Autolaunched flow, then it’s a simple choice. Use the Pause element (Working like magic), and configure it to resume your flow after 0 hours of current date-time. Please note that pausing the flow makes the rest of the flow run asynchronously in a separate transaction. https://forcepanda.wordpress.com/2020/02/04/how-to-cheat-flow-limits/comment-page-1/?unapproved=12451&moderation-hash=5450b3bb955c04592e053c4470232d5a#comment-12451
    Harshala Godse
    April 21, 2022 5:56 pm
    If your flow is an Autolaunched flow, then it’s a simple choice. Use the Pause element (Working like magic), and configure it to resume your flow after 0 hours of current date-time. Please note that pausing the flow makes the rest of the flow run asynchronously in a separate transaction. https://forcepanda.wordpress.com/2020/02/04/how-to-cheat-flow-limits/comment-page-1/?unapproved=12451&moderation-hash=5450b3bb955c04592e053c4470232d5a#comment-12451
    Ryan M
    April 25, 2022 8:08 pm
    I've tried this but can't get the Flow to Resume? Any thoughts on that?
    Tristan
    July 11, 2022 6:33 am
    Is there a way to add a Task to a record through Flows? For example, if Sales Call checkbox is True create new task called "Sales Call". When trying to migrate current workflows to Flows that have this I get the error, "We can’t migrate this workflow rule because it contains TASK workflow actions. Migrate to Flow doesn’t support this configuration." Thanks for any insight!!
    Nina Gonzalez
    August 17, 2022 12:41 am
    What is the best way to "get" records that have some variables in common with the records in the start element. The "get" records identify how the original records are updated. Start (probably scheduled flow) If record is blue. Get records that have the same Account and Record Name as the blue record but not the same status. If the Get record has a status of "done", then update the blue record to "cooked". If the Get record has a status of "frozen", then update the blue record to "uncooked". Can this been done in a loop?
    Graeme
    September 28, 2022 3:13 pm
    I'm wondering, is having a GET inside of a loop always considered bad or does it wholly depend on how many records are expected to be looped? I have a scenario where the loop is only ever expected to run 2 times and so I wonder how bad it really is to have that GET inside of the loop. I already fixed it by moving the GET outside of the loop and then filtering the GET collection inside the loop, but in terms of resource savings I do wonder if it was "necessary" or simply "a thing we do for the sake of best practices".
    Brett
    November 03, 2022 10:15 pm
    Can a Flow loop through a variable? IE. Loop until Variable = 10 rather than a collection set. Or do you need Apex for that?
    Jon
    November 12, 2022 12:07 am
    I would preface "Never perform a DML Statement within a Loop" section with a clause for screen flows. I would argue that it's fine to do so in screen flows so long as a screen exists inside the loop
    Ea
    March 14, 2023 1:01 pm
    Hi, when I need to set the related object field of, for this example contact, how can I do that?
    Brandon
    May 25, 2023 1:44 am
    So a little late but yes. Create a Single and a Multi record variable for the object. Create the loop and place a decision path within it (If status is done then path A if Frozen then path b). In path A create an assignment that sets the single record variable to Cooked (you can set several fields here), do the same in path B for uncooked. Then where both decision paths come back together create another assignment element that "Adds" your single record variable to the Multi variable. Upon exit of the loop run an update on multiple records referencing your multi variable. Hope that helps somebody in the future.
    Brandon
    May 25, 2023 1:46 am
    Create a number variable that defaults at 0. Within the loop have an assignment element that "Adds" 1 to your variable, have a decision that checks this count, when your variable exceeds it the path should exit the loop.
    Jacob
    August 16, 2023 8:03 pm
    What would the best practice be if you need to create a related record to a record within the loop? For example I need to create 10 Work Orders from a list of selected Assets from a Data table. But for each Work Order I need to create a related Case record as well. I can't create a collection of the Cases and then create them as I would need the record Ids to create the Work Orders.
    Eden
    April 18, 2024 8:47 pm
    Hi Ben, thank you for another great explanation. I'm trying to figure out in which cases it is not needed to use a loop, and I can simply use the Update Element. In case I want to update contact records based on specific conditions, that are true to a bunch of contacts, will the Update Element might not work for all of them? Will be happy to understand when it is a better practice to use the loop and when it is just complicating my flow.

Leave a Reply