Back to LinkedIn posts

LinkedIn post 12

Some Apex trigger gotchas

Some Apex trigger gotchas
(thanks to Dan Appleman's "Advanced Apex Programming in Salesforce" 🙏 )

1️⃣ Formula fields are stale in before triggers

In BEFORE triggers, formula fields can still show old values. The record changes have not been committed yet.
Formula.recalculateFormulas() can help, but it has limits. If you call it directly on records you are also changing, it can throw a DmlException. Clone the records first, then recalculate the formulas on the clones.

2️⃣ Lead conversion only shows up reliably in after triggers

The before update trigger runs during lead conversion, but isConverted is still false and the converted IDs are still null.
We can only confirm the conversion and read the new Account, Contact, and Opportunity IDs in the AFTER update context.

3️⃣ Delete triggers do not fire on cascade-deleted child records

When a master-detail parent is deleted, Salesforce deletes the child records automatically but the child delete triggers do not run.
If child-record logic needs to happen, put that logic in the parent’s before delete trigger.

4️⃣ Merge can skip update triggers on reparented child records

A merge fires the expected triggers on the records being merged: delete on the loser and update on the winner.
But the triggers do not fire on child records moved from the losing record to the winning record. If your logic assumes every field change runs through a trigger, that can leave data out of sync.

5️⃣ recalculateFormulas() does not cover every formula case

recalculateFormulas() is useful, but it is not the same as running after-trigger logic. Cross-object formulas and some field types may not recalculate the way you expect. Treat recalculateFormulas() as a narrow scope tool instead of a full replacement for after-trigger behavior.

graphical user interface, application