Sub topic 14
Working Alongside Apex Triggers and Other Flows
Real orgs rarely have one automation per object. An Opportunity might fire two before-save flows, an Apex trigger, three after-save flows, and a managed package trigger on one save. This chapter covers how those pieces interact and how to keep the result predictable.
This chapter assumes you have read the earlier chapters on before-save and after-save flows, the order of execution, shared governor limits, and recursion. You should also be able to read a basic Apex trigger.
What "coexist" means in practice
All automation on one save runs in one transaction. Three consequences follow:
- Governor limits are shared. A flow's SOQL queries and DML statements count against the same 100 and 150 limits as Apex in that transaction.
- Anything that fails can roll back the whole transaction, including work done by other automation.
- The order of execution decides what each piece sees. A later step sees the changes of an earlier step, and an earlier step does not see later changes.
The usual order of the relevant steps is below. Check the current Apex Developer Guide for the full list, because Salesforce adjusts it between releases.
The two points that matter most for coexistence:
- Before-save flows run before before-triggers. If both set the same field, the Apex trigger wins, because it runs last.
- After-save flows run after after-triggers. An after-save flow sees any changes the trigger made through DML, and the trigger does not see the flow's changes in the same pass.
Apex and flows on the same object
Who sets the field last
Suppose a before-save flow sets NextStep to Review large deal, and a before-update trigger also writes NextStep. The final value is the trigger's value. This is a common source of "my flow doesn't work" reports, because the debug log for the flow shows a correct assignment that was overwritten later.
To find these conflicts, open the debug log and look at the FLOW_START_INTERVIEWS and CODE_UNIT_STARTED lines. Their order shows which automation ran first.
Re-entering the transaction
When an after-save flow or an after trigger updates the same record, the save re-runs. Before-save flows, before triggers, and after triggers fire again, and so do after-save flows whose entry conditions are met.
Entry conditions are your main defense. Compare these two settings on an after-save flow that updates its own record:
| Setting | Effect on a second pass |
|---|---|
| Run: every time a record is updated and meets the condition | Flow runs again if the condition is still true |
| Run: only when a record is updated to meet the condition requirements | Flow runs only if the record did not meet the condition before this update |
On the second pass, $Record__Prior holds the values from the first pass's save. The "only when updated to meet" option compares against that prior state, so the flow does not loop on its own output. See the earlier recursion chapter for the details.
Apex has its own guard, which flows cannot read. A static variable in an Apex class lasts for the transaction, but a flow has no access to it. This means an Apex recursion guard does not stop a flow from re-firing, and a flow's entry condition does not stop a trigger from re-firing. You need a guard on each side.
public with sharing class OpportunityTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static void handleAfterUpdate(List<Opportunity> newList) {
List<Opportunity> toProcess = new List<Opportunity>();
for (Opportunity opp : newList) {
if (!processedIds.contains(opp.Id)) {
processedIds.add(opp.Id);
toProcess.add(opp);
}
}
if (toProcess.isEmpty()) {
return;
}
// Work on toProcess here.
}
}trigger OpportunityTrigger on Opportunity (after update) {
OpportunityTriggerHandler.handleAfterUpdate(Trigger.new);
}A guard that blocks every record after the first pass can hide legitimate second-pass changes. Keying on record Id, as above, is crude. If the second pass needs to react to a field a flow changed, compare Trigger.oldMap with Trigger.new for that field and skip the guard for it.
Calling Apex from a flow
When logic is too complex for flow elements, an after-save flow can call Apex through an invocable method. The method receives a list, because the flow can run for many records in one transaction.
public with sharing class FollowUpService {
@InvocableMethod(label='Create follow-up tasks' description='Creates one task per opportunity Id')
public static void createTasks(List<Id> opportunityIds) {
List<Task> tasks = new List<Task>();
for (Id oppId : opportunityIds) {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = oppId
));
}
insert tasks;
}
}The flow's Action element passes {!$Record.Id} to the method. In a bulk save, Flow batches these calls, so one invocation of createTasks may receive many Ids. Write invocable methods to loop over the list and use one DML statement, as above. A method that runs a query or DML per item can exhaust limits when a data load updates 200 records.
Choosing flow, Apex, or both
| Situation | Better fit |
|---|---|
| Simple field defaults and copying values | Before-save flow |
| Creating or updating related records with clear rules | After-save flow |
| Complex branching, large collections, or callouts that need fine control | Apex trigger or invocable Apex |
| Admins need to change the logic without deploying code | Flow |
| A strict, testable guard on recursion across many entry points | Apex handler framework |
A mixed design is fine. Keep each piece's job small and write down which automation owns which field.
Several flows on the same object
Multiple record-triggered flows on one object and trigger event run in the same transaction. Before-save flows run as a group, then after-save flows as a group. Within a group, the order is not guaranteed unless you set it.
Flow Trigger Explorer and trigger order
Flow Trigger Explorer is a Setup tool. Pick an object and a trigger event, and it lists the flows that run, grouped by type. From there you can assign each flow a Trigger Order number. Flows with a low assigned value run first, flows without a value run next, and flows with a high assigned value run last. Check the current Salesforce documentation for the exact range, which has changed over releases.
Use trigger order only when one flow depends on another's output. Examples:
- Flow A sets a normalized
Region__cin a before-save flow, and Flow B readsRegion__cin a decision. Give A an earlier order. - Flow A creates a Case, and Flow B on Case should run after another Case flow has set defaults.
If you need many ordering rules, consider merging the flows. One flow with clear Decision branches is easier to read than five flows with interlocking order numbers.
What a later flow sees
Within the before-save group, a later flow sees field values set by an earlier flow in $Record. In the after-save group, a later flow sees records created or updated by earlier flows, but only if it queries them with Get Records, because $Record is the triggering record as saved.
$Record__Prior for a flow in the same group still holds the values from before the whole transaction's save, not the values from before the earlier flow ran. Do not use it to detect what another flow changed.
Avoiding conflicts between automations
Use these habits on any object with more than one automation:
- Give each field one owner. If a flow and a trigger both write
Status__c, document why, or merge them. - Keep entry conditions specific. A flow with no condition runs on every save of every record, and also on the second pass.
- Prefer one flow per object, trigger event, and optimization type, with Decision elements for branches. This reduces ordering questions.
- Avoid an after-save flow that updates the triggering record. Use a before-save flow instead, which needs no extra DML and does not re-run the save. Use an after-save update only for work a before-save flow cannot do.
- Count shared limits during design. A data load of 200 records through an after-save flow with a Get Records inside a loop, plus an Apex trigger with a query, can hit the SOQL limit even if each piece looks small.
Testing the combination
Test the interaction, not only each piece. Because the flow and the trigger both fire in one insert, a single test can exercise both. The class below assumes the before-save flow from earlier in this tutorial is active and that OpportunityTrigger is deployed.
@IsTest
private class OpportunityCoexistenceTest {
@IsTest
static void flowAndTriggerBothRunInBulk() {
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Bulk deal ' + i,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
Amount = 200000
));
}
Test.startTest();
insert opps;
Test.stopTest();
Integer flowSet = [
SELECT COUNT() FROM Opportunity
WHERE Id IN :opps AND NextStep = 'Review large deal'
];
Assert.areEqual(200, flowSet, 'The before-save flow should set NextStep on every record.');
}
}Inserting 200 records matches the batch size of a data load. If the flow or trigger has a query or DML inside a loop, this test fails with a limit exception. Run it whenever you add automation to the object.
For manual debugging, use a debug log with the Workflow category at FINER and the Apex Code category at DEBUG. In Flow Builder, the Debug button runs a flow against a chosen record, and Flow Trigger Explorer confirms the expected order.
Exercise
An Opportunity has a before-save flow that sets NextStep to "Review large deal" and a before-update Apex trigger that sets NextStep to "Escalate". After a save, NextStep is "Escalate". Why, and how would you fix it so the flow's value is kept?
Show answer
Before-save flows run before before-triggers, so the trigger writes last and overwrites the flow's value. To keep the flow's value, remove the conflicting assignment from the trigger, or merge the logic so one piece owns NextStep. Setting a Trigger Order on the flow does not help here, because trigger order only sorts flows against other flows, not against Apex.
Exercise
An after-save flow updates a field on its own triggering record. The flow's run frequency is "every time a record is updated and meets the condition", and the condition stays true after the update. What happens, and which setting reduces the risk?
Show answer
The update re-runs the save, so the flow's entry condition is checked again. Because the condition is still true, the flow fires again, which can repeat until Salesforce stops the chain with a depth or limit error. Choose "only when a record is updated to meet the condition requirements", so the flow runs only when the record did not meet the condition before the update. A before-save flow is better still, because it changes the record without triggering a second save.
Exercise
Why must an invocable Apex method called from a record-triggered flow accept a List and avoid DML inside the loop?
Show answer
The flow can run for many records in one transaction, such as a 200-record data load, and Flow batches the calls to the method. A method that runs a query or DML for each item uses up the shared governor limits, so the transaction fails. Accept a list and use one DML statement for the whole list.