Sub topic 2
Designing Request and Response Classes
Assume you know basic Apex collections, SOQL, DML, and Flow variables. An invocable method should use wrapper classes when Flow needs several inputs or outputs. A wrapper class is a class that groups related values into one request or response object.
Designing request and response classes
Mark fields that Flow can see with @InvocableVariable. The request describes one operation. The response describes what happened.
public with sharing class AccountTaskCreator {
public class Request {
@InvocableVariable(label='Account Id' required=true)
public Id accountId;
@InvocableVariable(label='Task Subject')
public String subject;
}
public class Result {
@InvocableVariable(label='Task Id')
public Id taskId;
@InvocableVariable(label='Success')
public Boolean isSuccess;
}
@InvocableMethod(label='Create Follow-up Tasks')
public static List<Result> createTasks(List<Request> requests) {
List<Task> tasks = new List<Task>();
for (Request request : requests) {
tasks.add(new Task(
WhatId = request.accountId,
Subject = String.isBlank(request.subject)
? 'Follow up'
: request.subject,
ActivityDate = Date.today().addDays(7)
));
}
List<Database.SaveResult> saves = Database.insert(tasks, false);
List<Result> results = new List<Result>();
for (Database.SaveResult save : saves) {
Result result = new Result();
result.isSuccess = save.isSuccess();
result.taskId = save.isSuccess() ? save.getId() : null;
results.add(result);
}
return results;
}
}The method accepts a list and returns a list. The @InvocableVariable annotations expose the fields to Flow. Keep the response fields useful to the next Flow element, such as an ID, status, or error message.
Handling many flow interviews in one call
Flow can invoke an action with multiple requests. This is called bulk invocation. Build all records first, perform one DML statement, and return one result for each request in the original order.
Never put SOQL or DML inside the loop. Matching output order lets Flow associate each result with its input record.
Calling the method from Flow Builder
After deploying the class, add an Action element and select Create Follow-up Tasks. Flow displays the annotated request fields as inputs. Map the account ID and subject from Flow variables. Store the returned collection when the action runs in a collection context, then map fields such as taskId or isSuccess into later elements.
Exercise
Why should an invocable method return one response for every request?
Show answer
Flow can match each response to its input by position, even when the method processes many records in one transaction.