Sub topic 4
Exposing fields with @InvocableVariable
This chapter assumes you can write Apex classes with inner classes, collections, and SOQL. It also assumes you have built a simple flow in Flow Builder and have read the earlier chapters on @InvocableMethod and its signature rules. Here you will learn how Apex fields become the inputs and outputs that a flow author sees.
What the annotation does
An invocable method receives and returns Apex objects. A flow knows nothing about Apex classes, so it needs a description of which fields exist, what they are called, and which are mandatory. The @InvocableVariable annotation supplies that description.
A field with the annotation appears in Flow Builder:
- On an input class, the field becomes an input parameter on the Action element.
- On an output class, the field becomes an output value you can store in a flow variable.
A field without the annotation is invisible to the flow. It is still a normal Apex field, so your code can read and write it. It is neither filled from the flow nor returned to it.
Declaring annotated fields
Annotate member variables in a class. The method's parameter type is List<Request> and its return type is List<Result>, so those two classes carry the annotations.
public with sharing class DiscountCalculator {
public class Request {
@InvocableVariable(
label='Opportunity'
description='The opportunity to discount. Must include the Amount field.'
required=true
)
public Opportunity opp;
@InvocableVariable(
label='Discount Percent'
description='A number from 0 to 100.'
required=true
)
public Decimal discountPercent;
@InvocableVariable(
label='Reason'
description='Shown in the summary text.'
defaultValue='Flow discount'
placeholderText='For example, Renewal'
)
public String reason;
// No annotation: the flow cannot see or set this field.
public String internalNote;
}
public class Result {
@InvocableVariable(label='Discounted Amount')
public Decimal discountedAmount;
@InvocableVariable(label='Summary')
public String summary;
}
@InvocableMethod(
label='Calculate Discount'
description='Returns the discounted amount for each opportunity.'
)
public static List<Result> calculate(List<Request> requests) {
List<Result> results = new List<Result>();
for (Request req : requests) {
Result res = new Result();
Decimal amount = req.opp?.Amount;
Decimal percent = req.discountPercent;
if (amount == null || percent == null) {
res.summary = 'Amount or percent was missing.';
} else {
res.discountedAmount = amount - (amount * percent / 100);
String why = String.isBlank(req.reason) ? 'Discount' : req.reason;
res.summary = why + ': ' + percent + '% applied.';
}
results.add(res);
}
return results;
}
}The method adds exactly one Result for each Request, even when the input is incomplete. Earlier chapters explain why the output list must match the input list in size and order.
Attributes of @InvocableVariable
All attributes are optional. They control how the field looks and behaves in Flow Builder.
| Attribute | Effect |
|---|---|
| `label` | The name shown in Flow Builder. If omitted, the field's API name is shown. |
| `description` | Help text for the flow author. |
| `required` | When `true`, Flow Builder will not let the author save the Action element without a value for this input. The default is `false`. |
| `defaultValue` | A value, written as a string, used when the flow does not supply one. |
| `placeholderText` | Hint text shown in the empty input field. |
Treat label and description as mandatory in practice. A flow author maps these fields without reading your code, and a field called val2 with no description is easy to map wrongly.
What required really enforces
required=true is a design-time check in Flow Builder. It does not run when your Apex executes. If a flow passes a variable that happens to be empty at runtime, or if an Apex test calls the method directly, the field arrives as null. Write defensive code for every input, as the example does with the amount == null check.
Default values and blanks
A flow input that is not mapped, or is mapped to an empty variable, usually reaches Apex as null, not as an empty string. Use String.isBlank() for text and explicit null checks for numbers, as shown above. If you use defaultValue, remember that your own tests bypass Flow Builder. Calling new Request() in Apex does not apply the default, so the test sees null.
Supported field types
Annotated fields can hold the following:
| Category | Examples |
|---|---|
| Primitives | `String`, `Integer`, `Long`, `Decimal`, `Double`, `Boolean`, `Date`, `Datetime`, `Time`, `Id` |
| sObjects | A specific type such as `Account` or `Opportunity`, or the generic `SObject` |
| Apex-defined types | A class of your own whose fields carry the annotation |
| Collections | A `List` of any of the above |
Maps and sets are not supported. If you need a map-like structure, send two parallel lists or a list of Apex-defined objects. Note that parallel lists depend on matching positions, which is easy to break. A list of a small Apex-defined class is safer.
Fields that are lists
A field can itself be a List. In the flow, you map a collection variable to it. Your method then receives a list of requests, and each request holds its own list.
public with sharing class TagApplier {
public class Request {
@InvocableVariable(label='Record Id' required=true)
public Id recordId;
@InvocableVariable(label='Tags' description='A collection of text values.')
public List<String> tags;
}
@InvocableMethod(label='Count Tags')
public static List<Integer> countTags(List<Request> requests) {
List<Integer> counts = new List<Integer>();
for (Request req : requests) {
counts.add(req.tags == null ? 0 : req.tags.size());
}
return counts;
}
}Here the outer list is the batch of flow interviews, and tags is the collection for one interview. Keep those two levels distinct when you debug.
sObject fields
An sObject field is convenient because the flow can pass an entire record variable. There is a catch: the record only contains the fields the flow loaded. If the flow's Get Records element selected only Id and Name, then opp.Amount is null in your method. The description in the example says "Must include the Amount field" for that reason. For a field you control completely, accept an Id and query what you need inside the method, using one bulk-safe query for the whole list.
A field typed as the generic SObject lets the flow author pass any record type. The flow author then picks the object when configuring the action. This is flexible but moves type safety from compile time to runtime. Check getSObjectType() before you cast.
Rules and common errors
Most errors with this annotation come from a small set of rules.
- Annotate only public or global instance fields. Private fields, static fields, and local variables cannot be exposed. Use plain fields, not properties with
getandset. - The class must be visible to the method. A
publicinvocable method needspublicwrapper classes. If the method isglobal, the wrapper classes must beglobaltoo. - The classes used as parameter and return types belong to the method's contract. A class that has no annotated fields gives the flow nothing to map.
- Renaming an annotated field breaks existing flows. Flow Builder maps by the field's API name. Changing
labelordescriptionis safe, but renamingdiscountPercenttopercentinvalidates every flow that maps it. Add a new field and keep the old one until flows are migrated. - Adding a new required input also breaks active flows that do not map it. Add new inputs as optional.
- Removing a field that a flow references causes a save or activation error in that flow.
Checking that fields behave as expected
You can verify null handling and output shape without any flow. Construct the request in Apex and leave inputs unset, which is what a partially mapped flow looks like.
@IsTest
private class DiscountCalculatorTest {
@IsTest
static void returnsOneResultAndHandlesMissingPercent() {
DiscountCalculator.Request full = new DiscountCalculator.Request();
full.opp = new Opportunity(Name = 'A', Amount = 1000);
full.discountPercent = 10;
DiscountCalculator.Request incomplete = new DiscountCalculator.Request();
incomplete.opp = new Opportunity(Name = 'B', Amount = 500);
List<DiscountCalculator.Result> results =
DiscountCalculator.calculate(new List<DiscountCalculator.Request>{ full, incomplete });
Assert.areEqual(2, results.size(), 'One result per request');
Assert.areEqual(900, results[0].discountedAmount);
Assert.isNull(results[1].discountedAmount, 'Missing percent gives no amount');
Assert.areEqual('Discount: 10% applied.'.replace('Discount', 'Flow discount').length() > 0, true);
}
}The test does not rely on defaultValue or required. Both belong to Flow Builder, not to the Apex runtime.
How the fields appear to a flow author
When a flow author adds an Action element and selects your method, Flow Builder lists each annotated input field with its label, description, and placeholder. Required inputs are marked. After the action runs, each annotated output field is available as a value that can be stored in a flow variable. If the method returns a list, the author can also store the whole result as a collection and loop over it. The next chapters cover this configuration.
Summary of design advice
- Give every annotated field a clear
labeland adescriptionthat states units, format, and whether the field must be loaded on a record. - Make a field
requiredonly when the method cannot do anything useful without it, and still check fornull. - Prefer primitives and
Idfor inputs when you can. Use full sObjects when the flow already holds the record. - Keep annotated fields stable. Add rather than rename.
Exercise
A flow passes an Opportunity record variable into your invocable method, but req.opp.Amount is always null in Apex. The input field is marked required=true, and the flow mapping looks correct. What are two likely causes, and what are two ways to fix it?
Show answer
The likely causes are that the flow's Get Records element did not load the Amount field, so the record variable holds only some fields, or that the flow variable is empty at runtime because required=true is checked only in Flow Builder, not when Apex runs. To fix it, you can load Amount in the flow (select all fields or Amount explicitly), or change the input to an Id and query Amount inside the method with one SOQL query for the whole list. Adding a null check and returning a clear message in the result is also a good safeguard.
Exercise
You want to rename the annotated field discountPercent to percent in a class that active flows already use. Why is this risky, and how do you do it safely?
Show answer
Flow Builder maps inputs by the field's API name, so renaming the field breaks every flow that maps discountPercent. To migrate safely, add the new percent field as an optional input, keep discountPercent working (for example, use whichever one is set), update the flows one by one, and remove the old field only after no flow references it.