Sub topic 6
Handling many flow interviews in one call
This chapter assumes you know basic Apex (classes, collections, SOQL, DML) and the basics of Flow Builder. You should also know that Apex enforces governor limits per transaction.
Why the method receives a list
A flow interview is one running instance of a flow. When a record-triggered flow fires for 200 records in one save operation, Salesforce can group the Apex action calls from those interviews into a single call. Your @InvocableMethod then receives one list entry per interview.
That is why the method signature takes a List, even if your flow only ever seems to process one record. If you write the method as if the list always has one item, it will fail or hit limits as soon as data is loaded in bulk.
The ordering rule
If the method returns a list, the list must have the same size and order as the input. Entry n of the output goes back to interview n. Salesforce does not match results by ID or by any field. It matches them by position only.
A common mistake is to skip a failed or blank input and return a shorter list. That shifts every later result to the wrong interview. Always add exactly one output per input, even when that output only records a failure.
The bulk-safe pattern
Follow three steps:
- Loop over the inputs and collect what you need into collections.
- Run one SOQL query and one DML statement for the whole collection, outside any loop.
- Loop over the outcomes and build one result per input, in the original order.
The AccountTaskCreator class below follows this pattern. It builds one Task per request, then inserts them all together.
public with sharing class AccountTaskCreator {
public class Request {
@InvocableVariable(label='Account Id' description='Account that the task relates to' required=true)
public Id accountId;
@InvocableVariable(label='Task Subject' description='Defaults to Follow up if blank')
public String subject;
}
public class Result {
@InvocableVariable(label='Task Id')
public Id taskId;
@InvocableVariable(label='Is Success')
public Boolean isSuccess;
@InvocableVariable(label='Error Message')
public String errorMessage;
}
@InvocableMethod(
label='Create Follow-up Tasks'
description='Creates one follow-up task per request and returns one result per request.'
category='Account'
)
public static List<Result> createTasks(List<Request> requests) {
List<Task> tasks = new List<Task>();
for (Request req : requests) {
tasks.add(new Task(
WhatId = req.accountId,
Subject = String.isBlank(req.subject) ? 'Follow up' : req.subject,
ActivityDate = Date.today().addDays(7)
));
}
List<Database.SaveResult> saveResults = Database.insert(tasks, false);
List<Result> results = new List<Result>();
for (Integer i = 0; i < saveResults.size(); i++) {
Result res = new Result();
res.isSuccess = saveResults[i].isSuccess();
if (res.isSuccess) {
res.taskId = saveResults[i].getId();
} else {
res.errorMessage = saveResults[i].getErrors()[0].getMessage();
}
results.add(res);
}
return results;
}
}Two details keep the ordering correct:
- Each
Taskis added totasksin the same loop that readsrequests, sotasks[i]belongs torequests[i]. Database.insert(tasks, false)returns oneSaveResultper task, in the same order. Thefalseargument allows partial success. A bad record produces a failed result and does not stop the others.
Keeping the order when you skip work
Sometimes an input should not produce a task, for example when it has no account ID. You still owe the flow one result. Build the result list up front, with one entry per request. Then fill in the entries that did real work.
public with sharing class SlugGenerator {
@InvocableMethod(label='Make Slug' description='Lowercases text and replaces spaces with hyphens.')
public static List<String> makeSlugs(List<String> inputs) {
List<String> slugs = new List<String>();
for (String input : inputs) {
slugs.add(input == null ? null : input.trim().toLowerCase().replaceAll('\\s+', '-'));
}
return slugs;
}
}A null input produces a null output, so the list keeps its size and order.
Exercise
An invocable method receives 5 requests. Request 3 has a blank account ID, so you skip creating a task for it. You return a list of 4 results. What goes wrong, and how do you fix it?
Show answer
Results are matched to interviews by position, so interviews 4 and 5 receive the results meant for 5 and nothing. Interview 5 gets no result. Fix it by returning exactly 5 results: for request 3, add a result with isSuccess set to false and an error message, in position 3.