Sub topic 1
When Flow needs Apex
Prerequisites
Assume you know basic Apex classes, methods, lists, SOQL, DML, and Flow Builder variables and elements. You should also understand that Apex governor limits restrict database operations and other resources in one transaction.
When Flow needs Apex
Flow handles record updates, decisions, loops, and many common integrations. Use Apex when the required operation is difficult to express with declarative elements, must use a specialized API, needs complex calculations, or should be reused by several flows.
An invocable method is an Apex method that Flow can call as an Apex action. Flow supplies input values, Apex performs the work, and Flow receives output values.
Marking a method with @InvocableMethod
The @InvocableMethod annotation exposes a method in Flow Builder. The method must be static, because Flow calls it without creating an instance of the class.
public with sharing class SlugGenerator {
@InvocableMethod(
label='Make Slug'
description='Converts text to a URL-friendly slug.'
)
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;
}
}The label is the action name shown to Flow users. A description explains the action's purpose.
Signature and class rules you must follow
An invocable method must be public or global, static, and defined in a top-level Apex class. A class can contain only one invocable method. The method accepts a list and may return a list. Its input and output types can be primitives, sObjects, or supported wrapper classes.
The list matters even when a flow appears to process one record. Salesforce can invoke the method with multiple flow interviews. Your method must process every input and avoid database queries or DML statements inside loops.
Exposing fields with @InvocableVariable
A wrapper class groups related inputs or outputs. Mark each field that Flow should see with @InvocableVariable. These fields must be accessible, usually as public fields.
public class AccountRequest {
@InvocableVariable(required=true)
public Id accountId;
@InvocableVariable
public String subject;
}Use required=true for values the action cannot usefully process without. Give fields clear labels and descriptions when Flow administrators will configure the action.
Exercise
Why does an invocable method accept a list instead of a single value?
Show answer
Flow can call it for multiple records in one transaction, so the method must handle bulk input.