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?

  • use a separate record variable to save the current record in each iteration of the loop (at the end of the loop). Then iteration j can find the previous record i in the separate record – cropredy Sep 22 '19 at 23:53
  • @cropredy This should be an answer, not a comment. It's exactly what I would have said. – sfdcfox Sep 23 '19 at 1:31
  • Depending on the number of records to process and the degree of parallelism, I would check the risk of inconsistencies when two of these processes run in parallel and both would retrieve the same pair of next/previous records (don't know if the currently processed record is of the same type and you're trying to achieve something like a linked list, just on the persistence level). Transaction isolation would mean that during processing of two records in parallel the getRecords might not see the other new record currently also being processed. If this is not the scenario, then don't worry. – Magnus Kreth Sep 23 '19 at 9:27

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.