Sub topic 2
Marking a method with @InvocableMethod
This chapter assumes you can read and write basic Apex (classes, static methods, collections, SOQL) and that you know Flow Builder well enough to add an element to a flow and set variables. It also assumes you know that Apex runs under governor limits. Here you will learn what the @InvocableMethod annotation does, which attributes it accepts, and what happens between the flow and your method. The full signature rules, wrapper classes, and bulk behavior get their own chapters, so this one only previews them.
What the annotation does
@InvocableMethod marks a static Apex method as an action that a flow can call. When you save the class, Salesforce registers the method. Flow Builder then lists it as an Action element, in the Apex category or in a custom category you choose.
Without the annotation, Flow cannot see your method, however public it is. The annotation is the only link between the two.
A flow never calls your method once per record. Salesforce collects the inputs from every flow interview that reaches the action in the same transaction. It then passes them to your method as one list. A record-triggered flow that fires for 200 records in one batch can therefore call your method once with a list of 200 items. This is why every invocable method takes a list parameter.
The smallest working example
This class takes a list of strings and returns a list of strings.
public 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;
}
}Three things matter here:
- The method is
staticandpublic. - It has one parameter, a
List. - It returns a
Listwith the same number of items as the input, in the same order. Salesforce matches each result back to its interview by position.
In Flow Builder, add an Action element, search for "Make Slug", and map a text value to the input. The output is a text value for each interview. Flow shows the single input as inputs and the output as Outputs, because the method uses plain strings with no named fields. Wrapper classes (covered later) give you readable names.
Annotation attributes
All attributes are optional. They control how the action looks and behaves in Flow Builder.
| Attribute | Type | Purpose |
|---|---|---|
| `label` | String | The name shown in Flow Builder. If you omit it, Flow Builder shows the method name. |
| `description` | String | Help text shown when someone selects the action. |
| `category` | String | The group the action appears in on the action picker. Use it to keep related actions together. |
| `callout` | Boolean | Set to `true` if the method makes callouts to an external system. |
| `configurationEditor` | String | Names a custom property editor (a Lightning web component) that Flow Builder shows instead of the default input form. |
| `iconName` | String | An icon to display with the action, for example a Lightning Design System or static resource icon reference. |
The next example uses the three attributes you will set most often.
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;
}
}The @InvocableVariable annotations and the Request and Result design are covered in later chapters. For now, notice the structure. One annotated method takes a list of requests and returns a list of results. It inserts every task with one DML statement, then builds one result per task.
Writing good labels and descriptions
Flow builders are often admins who never open your code. The label and description are the documentation they see. A good label states the outcome ("Create Follow-up Tasks"), not the implementation ("TaskCreatorV2"). A good description states what happens to the data, including side effects such as records created or emails sent.
Changing a label later does not break flows that already use the action. Flows store a reference to the Apex class and method, not to the label. Renaming or deleting the class or method does break them, so treat the class and method names as part of a public API.
Rules the annotation enforces
The compiler checks these when you save the class. Deploying an invalid class fails.
- One invocable method per class. A class can hold other methods, but only one can carry
@InvocableMethod. If you need several actions, create several classes. - The method must be
static. Flow does not construct instances of your class. - The method must be
publicorglobal. Useglobalin managed packages that expose the action to subscribers. - The method takes at most one parameter, and it must be a list. This is the part people trip over most often. To pass several values, put them in a wrapper class as shown above.
- The method returns
voidor a list. If it returns a list, the list's element type must be supported. The usual choices are primitives,Id, sObjects, or an Apex class with@InvocableVariablefields.
These signatures are all valid:
public class ValidSignatures {
// Void return: the action produces no output
@InvocableMethod(label='Log Ids')
public static void logIds(List<Id> ids) {
System.debug(ids);
}
}The following shapes are not valid, and each fails at save time:
- A method that takes two parameters, such as
(Id a, String b). - A method that takes a single value instead of a list, such as
(String s). - A non-static method.
- A method that returns a single
Stringinstead ofList<String>. - A second
@InvocableMethodin the same class.
What happens at run time
When a flow reaches the action, the following sequence runs:
- Flow collects the mapped input values from the interview. If other interviews in the same transaction reach the same action, Flow collects their values too.
- Flow builds the list parameter and calls your method once, inside the current transaction.
- Your method runs with the user's normal governor limits. It shares those limits with the rest of the transaction, including the flow itself and any triggers.
- Flow reads the returned list and hands each element back to the interview that supplied the matching input.
- If the method throws an unhandled exception, the action fails. Flow routes to the fault connector if the flow has one. Otherwise the flow fails with an error. Error handling has its own chapter.
Because step 2 combines inputs from many interviews, never assume the list holds a single item. A test that passes one item proves very little. The testing chapter shows how to call the method with 200 items.
Testing the annotation behavior directly
The annotation changes nothing about how you call the method from Apex. You can call it like any other static method, which is how you test it. The following test calls the earlier SlugGenerator directly.
@IsTest
private class SlugGeneratorTest {
@IsTest
static void returnsOneSlugPerInputInOrder() {
List<String> inputs = new List<String>{ 'Hello World', null, ' Multiple Spaces ' };
List<String> slugs = SlugGenerator.makeSlugs(inputs);
Assert.areEqual(3, slugs.size(), 'One result per input');
Assert.areEqual('hello-world', slugs[0]);
Assert.isNull(slugs[1], 'Null input yields null output');
Assert.areEqual('multiple-spaces', slugs[2]);
}
}This test checks the two guarantees that Flow depends on. The first is the count: three inputs produce three outputs. The second is the order: each output sits at the same index as its input. It also covers a null input, which Flow can send when a mapped variable is empty.
Common mistakes
- Annotating a method that takes a single value. Wrap the value in a list, or define a request class and take
List<Request>. - Returning a shorter list. If an input produces no result, return a placeholder at that index, such as
nullor a result withisSuccess = false. Do not skip it. - Putting a query or DML statement inside the loop. The method receives many inputs at once, so a per-item query or DML statement can hit governor limits as soon as a flow runs on a batch of records.
- Forgetting that the method runs in the caller's context. The action does not start a new transaction. A failure can roll back the whole transaction the flow belongs to.
- Adding a second invocable method to a class. Split the class instead.
Exercise
A teammate writes @InvocableMethod public static String getName(Id accountId). Name every problem that prevents this from saving, and show the corrected signature.
Show answer
There are two problems. The parameter is a single Id, not a list. The return type is a single String, not a list. A corrected signature is public static List<String> getNames(List<Id> accountIds). The method must also return one name per input Id, in the same order.
Exercise
A record-triggered flow runs on 150 records in one transaction, and each interview reaches an Apex action whose method is annotated with @InvocableMethod. How many times does Salesforce call the method, and how many items does the list contain? What must the method return so each interview gets the right result?
Show answer
Salesforce calls the method once with a list of 150 items, because it groups the inputs from interviews in the same transaction. The method must return a list of 150 results in the same order as the inputs, so that the result at each index goes to the interview that supplied the input at that index.