· 2 min read

For Loops in Directus Flows

The less-than-documented way to iterate over an array in Directus Flows.

I’ve used Directus for a while now for a couple client projects, mostly as a backend/admin portal. Directus has a feature called Flows which is a no-code tool to build workflows or to automate some actions either when something in the database changes or on a schedule or manually, etc. In past years I’ve had limited success with Flows for what I was doing and I recently took another swing at using them.

The flow I wanted needed to iterate over every object in a collection, calculate a new rank for every item and update each item’s new rank value. Pretty basic feature and using Flows is perfect since I can hook into CRUD events easily and therefore I know the rank will always be up-to-date. Directus Flows even have an option to drop down into raw Javascript which is how I calculated the rank for each item. But, I found I couldn’t figure out how to update each item in the collection with its new rank value from the previous step.

It took a bit longer than I think it should have to find this Github discussion on the topic and I can’t believe its not clearly written in their docs.

Solution

The key to making a ‘for’ loop in Directus Flows is to use two Flows. First you need a flow to gather an array of items or whatever. Then use an Execute Flow step and pass that array of items you want to iterate over as the Payload to the next Flow.

// Place your array in the `Payload` textarea like so, this assumes `data` is an array
"{{ $last.data }}"

The placeholder text in the Payload textarea encourages you to send an object, and the docs also don’t seem to demonstrate anything other than an object as well. Without an array Directus sends the whole object to the next Flow, but an array is treated as individual objects where each is passed to the next Flow one-one. This is essentially a ‘for’ loop in the no-code world.

In my Flow I then update the collection being sure the Payload updates only the rank value:

// Now $last is an object from the prevous Flow's array
{
  "rank": "{{ $last.rank }}"
}

And a filter to only update the current object:

{
  "filter": {
    "id": {
      "_eq": "{{ $last.id }}"
    }
  }
}
    Share:
    Back to Blog