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 itprevious
)Thus, at the beginning of the loop, you set
previous.Next__c
tocurrent.Id
current.Previous__c
toprevious.Id
At the end of each loop iteration
previous
to a new collectionpreviousUpdates
current
toprevious
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 valuespreviousUpdates
// sets all the Next__c values