Sub topic 11
Using both: calling Apex from Flow
This chapter assumes you can build a simple record-triggered or screen flow, and that you know Apex basics such as classes, lists, maps, and SOQL. It also builds on the earlier chapters on governor limits and bulk-safe design.
Why combine the two
Flow and Apex do not compete on every requirement. A common pattern is to let a flow handle the parts admins understand and change often: the entry criteria, the decisions, and the screens. The flow then calls Apex for the one step that is hard to build declaratively, such as a calculation, a complex query, or a callout with custom parsing.
This keeps the code small and testable. It also keeps the process visible in Flow Builder, where admins can read it.
How an invocable method works
An invocable method is a static Apex method marked with @InvocableMethod. Flow Builder lists it as an Action that you can add to any flow. Three rules shape how you write one:
- The method must be
static, and a class can have only one@InvocableMethod. - It takes a single parameter, which is a
Listof either a primitive type, an sObject, or your own class. - If you use your own class, mark each field you want to expose with
@InvocableVariable.
The list parameter matters. When a record-triggered flow runs for many records in one transaction, Flow can pass all the requests to your method in one call. Your code should handle the whole list at once.
A worked example
The class below reduces the Amount of opportunities by a percentage. It collects the inputs into a map, runs one query, and issues one update, whatever the list size.
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;
}
}To use it, open a flow, add an Action element, and search for "Apply Discount". Map the flow's opportunity Id to opportunityId and a number to percent. The required=true setting makes Flow Builder reject the action until both inputs are mapped.
What happens at run time
The flow and the Apex method share one transaction. Queries and DML statements the Apex code uses count against the same governor limits as the flow's own elements. If the Apex code throws an unhandled exception, the whole transaction rolls back, unless the flow has a fault path.
Common errors
- Querying or updating inside a loop. Handling one request per iteration with its own SOQL or DML defeats the list parameter and can hit limits at 100 queries or 150 DML statements.
- Assuming one request per call. Reading only
requests[0]silently skips the other records. - Mismatched output order. If the method returns a list, it must return one result per input, in the same order. Otherwise flow outputs attach to the wrong records.
- Forgetting sharing.
with sharingrespects the running user's access. Use it unless you have a reason not to, and note that flows can run in system context, which changes what the user sees. - Missing tests. Production deployment requires Apex test coverage, and the invocable class counts toward it. Test it with a list of many requests, not one.
Deciding when to use the pattern
Reach for this pattern when the process belongs in Flow but one step needs code. If most of the logic ends up in Apex, consider moving the whole automation to a trigger. If the Apex step is trivial, consider whether a flow formula or element can do it.
Exercise
A record-triggered flow on Opportunity calls your invocable method, and 200 opportunities are updated in one data load. The method contains a SOQL query inside a for loop over the requests list. What goes wrong, and how do you fix it?
Show answer
The loop runs the query once per request, so 200 requests use 200 queries and exceed the limit of 100 SOQL queries per synchronous transaction. The whole transaction fails. Fix it by collecting the Ids into a Set or Map first, running one query with WHERE Id IN :ids, and then looping over the results in memory.