Sub topic 11
Using both: calling Apex from Flow
This chapter shows how a flow calls Apex through an invocable method. It assumes you know the Salesforce data model, can find your way around Setup, have built a simple record-triggered flow, and understand variables, loops, and collections. It builds on the earlier chapters about governor limits, bulk-safe design, and the decision framework.
Why combine the tools
The decision framework often ends with "both." Flow is good at orchestration: it starts on a record change, branches on conditions, and is easy for an admin to read and edit. Apex is good at logic that is awkward or impossible to express declaratively, such as complex calculations, custom data structures, and callouts that need fine-grained control.
You do not have to choose one tool for the whole requirement. A flow can handle the trigger, the entry conditions, and the routing, then call a small piece of Apex for the one step that needs code. This keeps the admin-friendly parts visible in Flow and confines code to a narrow, testable unit.
Typical reasons to call Apex from a flow:
- A calculation needs loops, maps, or recursion that Flow handles poorly.
- The step needs an API that Flow does not expose, such as certain callouts or platform classes.
- The same logic must be reused from several flows, and from other Apex.
- You want unit tests that cover the logic in isolation.
The invocable method contract
An invocable method is a static Apex method annotated with @InvocableMethod. Once it is deployed, it appears in Flow Builder's Action element, under the name you give it in the label attribute.
The rules are strict, and breaking them causes compile errors:
- The method must be
staticandpublicorglobal. - A class can contain only one
@InvocableMethod. - The method takes at most one parameter, and that parameter must be a list. The list can hold primitives, sObjects, or a list of a custom Apex class.
- The return type is either
voidor a list. - To pass several named inputs, wrap them in an inner class whose fields use
@InvocableVariable.
Because the parameter is always a list, the contract itself pushes you toward bulk-safe design. When a record-triggered flow runs for many records in one transaction, Flow can batch the calls, and your method receives all of those requests in a single invocation.
A worked example
The following class is the example from the plan. It reduces the Amount of opportunities by a percentage that the flow supplies.
public with sharing class ApplyDiscountAction {
public class Request {
@InvocableVariable(required=true)
public Id opportunityId;
@InvocableVariable(required=true)
public Decimal percent;
}
@InvocableMethod(label='Apply Discount' description='Reduces the Amount of each opportunity by the given percent')
public static void apply(List<Request> requests) {
Map<Id, Decimal> percentById = new Map<Id, Decimal>();
for (Request r : requests) {
percentById.put(r.opportunityId, r.percent);
}
List<Opportunity> opps = [
SELECT Id, Amount FROM Opportunity WHERE Id IN :percentById.keySet()
];
for (Opportunity opp : opps) {
if (opp.Amount != null) {
opp.Amount = opp.Amount * (100 - percentById.get(opp.Id)) / 100;
}
}
update opps;
}
}Read it in three parts.
- The inner class.
Requestdefines the inputs. Each@InvocableVariablefield becomes an input in Flow Builder. Withrequired=true, Flow Builder refuses to save the flow unless the field is mapped. - The map. The loop collects every request into a
Map<Id, Decimal>. This gives one place to look up the percentage for each opportunity. - One query, one update. The method runs a single SOQL query for all the opportunities, adjusts them in memory, and issues a single DML statement. It uses one query and one DML statement whether it receives 1 request or 200.
The class uses with sharing, so the query respects the running user's record access. That is usually the safer default, but note that sharing rules do not enforce field-level security. If the flow can run for users who lack edit access to Amount, consider WITH USER_MODE in the query and update as user opps; for the DML.
Calling the method from a flow
After deployment, you add the action in Flow Builder:
- Open the flow, for example a record-triggered flow on Opportunity.
- Add an Action element and search for "Apply Discount". Invocable methods appear in the Apex category by default, and the category does not change with the
categoryattribute you can set on the annotation. - Map each input. For
opportunityId, use{!$Record.Id}. Forpercent, use a number, a variable, or a formula. - Save and activate.
If the flow needs to run the action for each item in a collection, you have a choice. You can put the Action inside a Loop, which calls Apex once per iteration, or you can build a collection of Request records and pass it to one call. The second approach is the one the method is designed for.
Passing a collection correctly
An Apex-defined type is available to Flow only if the class is declared with the right access and the fields carry @InvocableVariable. To call the method once for many records, create a collection variable of the Apex-defined type Request and assign the values inside the loop, then call the action after the loop ends.
A record-triggered flow already runs in bulk, so with $Record you often do not need your own loop at all. Flow batches the interviews for you and sends one list to the Apex action. Build your own collection only when a single flow interview needs to send several requests, for example one per related record.
Governor limits across the boundary
The earlier chapter on governor limits explained that Flow and Apex share one set of limits within a transaction. Calling Apex from Flow does not give you a fresh allowance. The query and DML inside the invocable method count against the same totals as the flow's own Get Records and Update Records elements, and against any trigger that fires in the same transaction.
Practical consequences:
- A flow with several Get Records elements that calls an Apex method running another query uses all of those queries from one budget.
- An action inside a loop that calls Apex per iteration, with a query in the method, can reach the SOQL limit of 100 for synchronous transactions quickly. Pass one list instead.
- If the method throws an unhandled exception, the whole transaction rolls back, including the flow's earlier changes.
Returning values and handling errors
An invocable method can return a list of values to the flow. The returned list must have one entry per input request, in the same order. Flow matches outputs to inputs by position, so a wrong order or a wrong length produces confusing results.
Here is a variant that returns a result object for each request, so that the flow can branch on failure instead of rolling everything back.
public with sharing class SafeDiscountAction {
public class Request {
@InvocableVariable(required=true)
public Id opportunityId;
@InvocableVariable(required=true)
public Decimal percent;
}
public class Result {
@InvocableVariable
public Boolean success;
@InvocableVariable
public String message;
}
@InvocableMethod(label='Apply Discount Safely')
public static List<Result> apply(List<Request> requests) {
Set<Id> ids = new Set<Id>();
for (Request r : requests) {
ids.add(r.opportunityId);
}
Map<Id, Opportunity> oppsById = new Map<Id, Opportunity>(
[SELECT Id, Amount FROM Opportunity WHERE Id IN :ids]
);
List<Result> results = new List<Result>();
List<Opportunity> toUpdate = new List<Opportunity>();
for (Request r : requests) {
Result res = new Result();
Opportunity opp = oppsById.get(r.opportunityId);
if (opp == null || opp.Amount == null) {
res.success = false;
res.message = 'Opportunity not found or has no Amount';
} else if (r.percent < 0 || r.percent > 100) {
res.success = false;
res.message = 'Percent must be between 0 and 100';
} else {
opp.Amount = opp.Amount * (100 - r.percent) / 100;
toUpdate.add(opp);
res.success = true;
}
results.add(res);
}
update toUpdate;
return results;
}
}The method validates each request, records the outcome in a Result at the same index, and updates only the valid records. In the flow, store the returned collection and use a Decision element to handle failures.
One caveat: if the same opportunity appears in two requests, the second request reads the already-reduced Amount from the shared object in the map, so the discounts compound. Decide whether that is acceptable, or reject duplicates.
Testing the combination
Test the Apex in isolation with a unit test that calls the method directly. Pass a list that covers the normal case, the invalid cases, and a large batch. Then test the flow with a record change that fires it, since an Apex test cannot see inside the flow's decisions unless the flow is active and runs in the test's transaction.
@IsTest
private class SafeDiscountActionTest {
@IsTest
static void appliesAndRejects() {
Opportunity good = new Opportunity(
Name = 'Good', StageName = 'Prospecting',
CloseDate = Date.today().addDays(30), Amount = 1000
);
Opportunity noAmount = new Opportunity(
Name = 'Empty', StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
insert new List<Opportunity>{ good, noAmount };
SafeDiscountAction.Request r1 = new SafeDiscountAction.Request();
r1.opportunityId = good.Id;
r1.percent = 10;
SafeDiscountAction.Request r2 = new SafeDiscountAction.Request();
r2.opportunityId = noAmount.Id;
r2.percent = 10;
List<SafeDiscountAction.Result> results =
SafeDiscountAction.apply(new List<SafeDiscountAction.Request>{ r1, r2 });
Assert.isTrue(results[0].success);
Assert.isFalse(results[1].success);
good = [SELECT Amount FROM Opportunity WHERE Id = :good.Id];
Assert.areEqual(900, good.Amount);
}
}Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Query or DML inside a loop in the method | Hits governor limits when flow sends many requests | Collect IDs first, then query and update once |
| Action placed inside a flow loop | One Apex call per iteration | Build a collection and call once after the loop |
| Returning a list of the wrong length | Outputs misaligned with inputs | Add one result per request, in order |
| Two `@InvocableMethod` annotations in one class | Compile error | Split into separate classes |
| Changing a method signature after flows use it | Active flows can break | Add a new method or class, then migrate the flows |
| Updating the triggering record in an after-save flow through Apex | Extra save and possible re-entry | Use a before-save flow, or follow the guidance on mixed automation |
Design guidance
Keep the invocable class thin. Put business rules in a separate service class that other code can also call, and let the invocable method translate between Flow's request objects and that service. Name the action's label and description for admins, because those strings are what they see in Flow Builder. Document who owns the class, since an admin may change the flow without knowing the Apex it depends on.
Exercise
A record-triggered flow on Opportunity calls an invocable method once for each opportunity inside a Loop element. The method runs one SOQL query. A user updates 150 opportunities with a data load. What goes wrong, and how do you fix it?
Show answer
The method is called once per opportunity, so it runs 150 queries in one synchronous transaction, which exceeds the limit of 100 SOQL queries and fails the transaction. Fix it by moving the Action out of the loop. Build a collection of request records and call the method once, or rely on the record-triggered flow's own bulk batching. The method then receives a list and runs one query for all requests.
Exercise
Your invocable method takes List<Request> and returns List<Result>. For three requests it returns only two results because it skips an invalid request. Why is this a problem?
Show answer
Flow matches outputs to inputs by position. Skipping one result shifts the later outputs so they refer to the wrong requests, and the list length no longer matches. Add a result for every request, with a failure flag and message for the invalid one, so the order stays aligned.