[SalesForce] Access index of sObject collection using flow builder loop

I'm using process builder to auto launch a flow. I pass an id to the flow and use the getRecords element to query for a collection of records that returns the records in descending order based on a datetime field. What I'm trying to do is loop over the records and assign the next/previous records into lookup fields that exist on the same sObject.

For example, if I have 5 records, the first record wouldn't have a next__c record, but I would need to grab the 2nd index in the collection to populate the previous__c field of the current record in loop. When I loop over the 2nd iteration in the collection, I would need to access the 1st index of the collection to populate the next__c field value and then the 3rd index of the collection to populate the previous__c field value. Is there a way to access the collection indexes? Or, some other way to accomplish this using flow? Or, do I have to resort to Apex to handle this process?

Best Answer

While in Lightning Flow you can't access record indices in a collection, you can go back to programming techniques first seen in COBOL

As you loop through your fetched records, you will copy at the end of the loop the current record to a separate record variable of the same type (call it previous)

Thus, at the beginning of the loop, you set

  • previous.Next__c to current.Id
  • current.Previous__c to previous.Id

At the end of each loop iteration

  • add previous to a new collection previousUpdates
  • copy current to previous

You need a decision block to handle the first loop iteration when there is no previous sobject.

Once the loop is exhausted, you update

  • records // sets all the Previous__c values
  • previousUpdates // sets all the Next__c values