Apex Triggers: Complete Guide with Best Practices and Interview Questions
Welcome to the comprehensive guide on Apex Triggers! This module will take you from the fundamentals to advanced concepts, equipping you with the skills to write robust and efficient trigger logic in Salesforce.
What is an Apex trigger?
An Apex trigger is Apex code that runs before or after records are inserted, updated, deleted or undeleted. Use a before trigger to change fields on the same records without DML, and an after trigger when you need record Ids or related records. Keep one trigger per object, with logic in a handler class that handles 200 records at once.
- Events: before and after insert, update and delete, plus after undelete.
- Context variables such as Trigger.new, Trigger.oldMap and Trigger.operationType tell you what fired the trigger.
- Never put SOQL or DML inside a loop; collect Ids, query once and use Maps.
- Control recursion with a static Set of processed record Ids, not a single static Boolean.
- Test with 200 or more records to prove the trigger is bulk-safe.
1. Introduction to Apex Triggers
Apex Triggers are powerful tools in Salesforce for automating business processes and enforcing custom logic before or after a record is saved, deleted, or undeleted. They are similar to database triggers but specifically for Apex code in the Salesforce environment.
What is an Apex Trigger?
An Apex Trigger is a piece of Apex code that executes before or after DML (Data Manipulation Language) events on Salesforce records — including insert, update, delete, and undelete operations.
Why Use Apex Triggers?
- Complex Business Logic: Implement custom validation rules, update related records, or interact with external systems.
- Data Integrity: Enforce sophisticated data integrity rules that standard validation rules cannot handle.
- Automation: Automate processes that require code — calculations, data aggregations, or complex record relationships.
- Prevent Inefficient Operations: Block certain operations or ensure data consistency.
Triggers vs. Declarative Tools
Choose Flow or Apex based on the requirements, maintainability, and execution behavior. Support for Workflow Rules and Process Builder ended on December 31, 2025; existing automation continues to run, and legacy automation should be migrated to Flow.
- Declarative Tools: No code required, easier to build and maintain, faster for simpler automation.
- Apex Triggers: Code-based logic for requirements such as complex data manipulation and coordinating asynchronous callouts.
Basic Syntax
trigger TriggerName on ObjectApiName (trigger_events) {
// Your Apex code logic here
}
trigger AccountTrigger on Account (before insert, after update) {
if (Trigger.isInsert && Trigger.isBefore) {
System.debug('Executing before insert on Account');
}
if (Trigger.isUpdate && Trigger.isAfter) {
System.debug('Executing after update on Account');
}
}
2. Understanding Trigger Events
Apex Triggers can execute at different stages of a DML operation. Understanding these events is fundamental to writing effective and efficient triggers.
Before Events (before insert, before update, before delete)
Fire before a record is saved to the database. Ideal for:
- Validating or modifying field values on the record being processed.
- Preventing a DML operation by adding errors.
- Populating fields that should be set before saving.
Trigger.oldMapis not available inbefore insert— there is no old version of the record.
trigger OpportunityValidationTrigger on Opportunity (before insert) {
for (Opportunity opp : Trigger.new) {
if (opp.CloseDate == null) {
opp.addError('Close Date is required for all new opportunities.');
}
}
}
After Events (after insert, after update, after delete, after undelete)
Fire after a record has been saved to the database. Records now have an ID assigned (for inserts). Ideal for:
- Accessing the record's newly assigned ID.
- Performing operations on related records.
- Sending emails or enqueueing asynchronous work for callouts to external systems.
- Creating or updating other records based on the current record's state.
trigger AccountContactCreationTrigger on Account (after insert) {
List<Contact> contactsToInsert = new List<Contact>();
for (Account acc : Trigger.new) {
contactsToInsert.add(new Contact(
FirstName = 'Primary',
LastName = acc.Name + ' Contact',
AccountId = acc.Id
));
}
if (!contactsToInsert.isEmpty()) {
insert contactsToInsert;
}
}
Order of Execution
Salesforce has a defined order of execution when a record is saved. Key stages:
- Original record loaded from database (or initialized for insert).
- New record values loaded from request, overwriting old values.
- System validation rules run.
- Before-save record-triggered flows run.
beforetriggers execute.- System validation and custom validation rules run.
- Duplicate rules run.
- Record saved to database (not yet committed).
aftertriggers execute.- Assignment rules, workflow rules, and escalation rules run as applicable.
- After-save record-triggered flows run later in the save process.
- Roll-up summary fields calculated.
- Commit to database.
3. Trigger Context Variables
Context variables provide access to the records that caused the trigger to fire, as well as the execution context. These are crucial for writing dynamic and efficient trigger logic.
Trigger.new— List of new sObject record versions. Available ininsert,update,undelete. Records can be modified inbeforetriggers.Trigger.old— List of old sObject record versions. Available inupdateanddelete. Read-only.Trigger.newMap— Map of IDs to new record versions. Available inbefore update,after insert,after update,after undelete.Trigger.oldMap— Map of IDs to old record versions. Available inbeforeandafter updateanddelete. Ideal for comparing old and new values during updates.Trigger.isExecuting—trueif the current context is a trigger, including recursive invocations. Use it to identify trigger context, not to detect recursion.Trigger.isInsert/Trigger.isUpdate/Trigger.isDelete/Trigger.isUndelete— Identifies the DML operation type.Trigger.isBefore/Trigger.isAfter— Identifies the execution phase.
trigger MyAccountTrigger on Account (before insert, before update, after insert, after update) {
if (Trigger.isBefore) {
if (Trigger.isInsert) {
for (Account acc : Trigger.new) {
if (acc.BillingCity == null) {
acc.BillingCity = 'Unknown';
}
}
} else if (Trigger.isUpdate) {
for (Account newAcc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(newAcc.Id);
if (newAcc.Rating == 'Hot' && oldAcc.Rating != 'Hot') {
newAcc.Description = 'Hot account identified by trigger.';
}
}
}
} else if (Trigger.isAfter) {
if (Trigger.isInsert) {
List<Opportunity> newOpps = new List<Opportunity>();
for (Account acc : Trigger.new) {
if (acc.NumberOfEmployees > 1000) {
newOpps.add(new Opportunity(
Name = 'Large Account Opp for ' + acc.Name,
AccountId = acc.Id,
CloseDate = Date.today().addMonths(3),
StageName = 'Prospecting'
));
}
}
if (!newOpps.isEmpty()) insert newOpps;
} else if (Trigger.isUpdate) {
List<Task> followUps = new List<Task>();
for (Account newAcc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(newAcc.Id);
if (newAcc.OwnerId != oldAcc.OwnerId) {
followUps.add(new Task(WhatId = newAcc.Id,
Subject = 'Review account owner change',
Status = 'Not Started', Priority = 'Normal'));
}
}
if (!followUps.isEmpty()) insert followUps;
}
}
}
4. Trigger Best Practices & Frameworks
One Trigger Per Object
Have only one trigger per sObject. Salesforce does not guarantee execution order between multiple triggers on the same object. Route all logic through a single trigger and delegate to a handler class.
Trigger Handler Pattern
The trigger acts as a dispatcher, calling methods in a separate Apex handler class based on context variables. This keeps the trigger lean and business logic testable and maintainable. The examples in this guide are alternatives; do not deploy multiple Account triggers together. For this handler, define and assign the custom permissions Change_Account_Name and Bypass_Account_Trigger to authorize name changes and trigger bypass, respectively.
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
AccountTriggerHandler handler = new AccountTriggerHandler();
if (Trigger.isBefore) {
if (Trigger.isInsert) handler.onBeforeInsert(Trigger.new);
else if (Trigger.isUpdate) handler.onBeforeUpdate(Trigger.new, Trigger.oldMap);
else if (Trigger.isDelete) handler.onBeforeDelete(Trigger.old, Trigger.oldMap);
} else if (Trigger.isAfter) {
if (Trigger.isInsert) handler.onAfterInsert(Trigger.new, Trigger.newMap);
else if (Trigger.isUpdate) handler.onAfterUpdate(Trigger.new, Trigger.oldMap);
else if (Trigger.isDelete) handler.onAfterDelete(Trigger.old, Trigger.oldMap);
else if (Trigger.isUndelete) handler.onAfterUndelete(Trigger.new, Trigger.newMap);
}
}
public class AccountTriggerHandler {
private static Boolean bypassTrigger = false;
public class BypassException extends Exception {}
public static void bypassTriggerExecution() {
if (!FeatureManagement.checkPermission('Bypass_Account_Trigger')) {
throw new BypassException('Trigger bypass permission is required.');
}
bypassTrigger = true;
}
public static void resumeTriggerExecution() { bypassTrigger = false; }
public static Boolean isTriggerBypassed() { return bypassTrigger; }
private Boolean isBypassed() { return bypassTrigger; }
public void onBeforeInsert(List<Account> newAccounts) {
if (isBypassed()) return;
for (Account acc : newAccounts) {
if (acc.Industry == null) acc.Industry = 'Other';
}
}
public void onBeforeUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) {
if (isBypassed()) return;
for (Account newAcc : newAccounts) {
Account oldAcc = oldMap.get(newAcc.Id);
if (newAcc.Name != oldAcc.Name && !FeatureManagement.checkPermission('Change_Account_Name')) {
newAcc.Name.addError('Account Name changes require the Change Account Name permission.');
}
}
}
public void onBeforeDelete(List<Account> oldAccounts, Map<Id, Account> oldMap) {
if (isBypassed()) return;
for (Account acc : oldAccounts) {
if (acc.NumberOfEmployees > 100) {
acc.addError('Cannot delete accounts with more than 100 employees.');
}
}
}
public void onAfterInsert(List<Account> newAccounts, Map<Id, Account> newMap) {
if (isBypassed()) return;
List<Task> tasks = new List<Task>();
for (Account acc : newAccounts) {
tasks.add(new Task(
Subject = 'Follow up with ' + acc.Name,
WhatId = acc.Id,
Status = 'Not Started',
Priority = 'Normal'
));
}
if (!tasks.isEmpty()) insert tasks;
}
public void onAfterUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) {
if (isBypassed()) return;
List<Contact> contactsToUpdate = new List<Contact>();
Set<Id> changedAccountIds = new Set<Id>();
for (Account newAcc : newAccounts) {
Account oldAcc = oldMap.get(newAcc.Id);
if (newAcc.BillingCity != oldAcc.BillingCity ||
newAcc.BillingState != oldAcc.BillingState ||
newAcc.BillingCountry != oldAcc.BillingCountry) {
changedAccountIds.add(newAcc.Id);
}
}
if (!changedAccountIds.isEmpty()) {
Map<Id, Account> newMap2 = new Map<Id, Account>(newAccounts);
for (Contact con : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :changedAccountIds]) {
Account newAcc = newMap2.get(con.AccountId);
con.MailingCity = newAcc.BillingCity;
con.MailingState = newAcc.BillingState;
con.MailingCountry = newAcc.BillingCountry;
contactsToUpdate.add(con);
}
if (!contactsToUpdate.isEmpty()) update contactsToUpdate;
}
}
public void onAfterDelete(List<Account> oldAccounts, Map<Id, Account> oldMap) {
if (isBypassed()) return;
for (Account acc : oldAccounts) {
System.debug('Account deleted: ' + acc.Name + ' (' + acc.Id + ')');
}
}
public void onAfterUndelete(List<Account> newAccounts, Map<Id, Account> newMap) {
if (isBypassed()) return;
for (Account acc : newAccounts) {
System.debug('Account undeleted: ' + acc.Name + ' (' + acc.Id + ')');
}
}
}
Bulkification
Record triggers process records in batches, normally up to 200 records per invocation. Handle each collection efficiently, and keep SOQL and DML outside for loops. A transaction can invoke the trigger for more than one batch. Collect relevant IDs, query related records once per invocation, and use maps to associate them with their parents. Bulkification reduces repeated database operations, but the number of related records and the total transaction limits still need consideration.
// Collect IDs first, then query the related records once.
Set<Id> accountIds = new Set<Id>();
for (Account acc : Trigger.new) {
accountIds.add(acc.Id);
}
List<Contact> contacts = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds];
Map<Id, List<Contact>> contactsByAccountId = new Map<Id, List<Contact>>();
for (Contact con : contacts) {
if (!contactsByAccountId.containsKey(con.AccountId)) {
contactsByAccountId.put(con.AccountId, new List<Contact>());
}
contactsByAccountId.get(con.AccountId).add(con);
}
for (Account acc : Trigger.new) {
List<Contact> related = contactsByAccountId.get(acc.Id);
if (related != null) {
System.debug(acc.Name + ' has ' + related.size() + ' contacts.');
}
}
Error Handling
Use sObject.addError() in before triggers to prevent saving and show user-friendly errors in the Salesforce UI.
trigger CaseStatusValidation on Case (before update) {
for (Case newCase : Trigger.new) {
Case oldCase = Trigger.oldMap.get(newCase.Id);
if (oldCase.Status == 'Closed' && newCase.Status == 'Open') {
newCase.addError('Cannot re-open a Closed case. Create a new case instead.');
}
}
}
How do partial-success DML and rollback work?
Use partial-success DML when callers need a result for each record, and inspect every result. An addError() call rejects the affected record; with all-or-none DML, an error causes the operation to fail. With Database.insert(records, false) or its update and delete equivalents, eligible records can succeed while failed records return errors. Successful operations are still part of the enclosing transaction and roll back if that transaction fails or is rolled back. Salesforce can retry eligible records during partial processing, so trigger logic must tolerate re-entry and must not rely on a transaction-wide static flag to identify records already handled.
How should trigger logic enforce access?
Choose the intended access policy explicitly. Apex triggers run in system mode, so do not assume that the initiating user's sharing, object permissions, or field permissions automatically restrict trigger logic. Sharing declarations and database operation modes serve different purposes; apply sharing and CRUD/FLS checks where the operation requires user access. User-mode SOQL and DML can enforce the running user's access, while system-mode operations need deliberate authorization. For Apex API version 67.0 and later, database operations default to user mode; specify the intended mode explicitly when clarity or compatibility matters. Test both authorized and unauthorized paths.
Bypassing Triggers
For migrations or integrations, use a controlled and authorized bypass appropriate to the operation, and restore its state afterward. The handler flag below applies only within the current Apex transaction; an external migration cannot configure it independently. An external process needs an explicit, access-controlled mechanism evaluated in each transaction, with a plan to restore the configuration.
public class DataMigrationService {
public static void importAccounts(List<Account> accountsToImport) {
Boolean wasBypassed = AccountTriggerHandler.isTriggerBypassed();
if (!wasBypassed) AccountTriggerHandler.bypassTriggerExecution();
try {
insert accountsToImport;
} finally {
if (!wasBypassed) AccountTriggerHandler.resumeTriggerExecution();
}
}
}
5. Handling Recursive Triggers
Recursion is re-entry into trigger logic caused by another operation in the same transaction. It can terminate normally, or repeated work can exceed trigger depth or other limits. Identify the operation that causes re-entry and make the resulting changes converge.
How can change-based logic prevent unnecessary recursion?
Prefer idempotent logic that acts only on the relevant change. Set fields on the current records in a before trigger, so no additional update is required. A transaction-wide static boolean can suppress later batches or partial-success retries and should not be used as a general recursion guard.
trigger AccountRatingTrigger on Account (before update) {
for (Account newAcc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(newAcc.Id);
if (newAcc.Rating == 'Hot' && oldAcc.Rating != 'Hot') {
newAcc.Description = 'Hot account: follow up required.';
}
}
}
How should a guard be scoped?
When an operation must update separate records and change-based logic alone is insufficient, scope a guard to the operation and affected record IDs. Remove the IDs in a finally block so later independent work can proceed. A guard prevents only the re-entry it covers; it does not replace a correct comparison or make after-trigger records writable. The example below guards only updates made through this method. Callers must still determine whether each description needs to change, and must use it only where updating those records is valid for the current trigger event.
public class AccountUpdateGuard {
private static Set<Id> activeIds = new Set<Id>();
public static void updateDescriptions(Map<Id, String> descriptions) {
List<Account> updates = new List<Account>();
Set<Id> acquiredIds = new Set<Id>();
for (Id accountId : descriptions.keySet()) {
if (!activeIds.contains(accountId)) {
acquiredIds.add(accountId);
updates.add(new Account(Id = accountId,
Description = descriptions.get(accountId)));
}
}
if (updates.isEmpty()) return;
activeIds.addAll(acquiredIds);
try {
update updates;
} finally {
activeIds.removeAll(acquiredIds);
}
}
}
Static variables are scoped to an Apex transaction.
System.runAs()changes the test user context; it does not start a fresh transaction or reset static variables. Partial-success retries can also retain static state.
6. Testing Apex Triggers
Production deployment coverage depends on the selected test level. RunLocalTests and RunAllTestsInOrg apply an overall Apex coverage requirement and require some coverage for every trigger; RunSpecifiedTests and RunRelevantTests apply coverage requirements to each deployed class and trigger. Check the requirements for the selected deployment option. Write tests for positive, negative, and bulk scenarios, including batches of 200 records.
The following tests target the dispatcher and handler in section 4. The address test uses example state and country values; replace them with values valid for the org if State and Country/Territory Picklists are enabled. Test the name-change permission separately with users who have and lack the custom permission, and verify both the saved value and any returned error. Configure permission assignments in test setup without depending on a particular profile name.
@isTest
private class AccountTriggerTest {
@isTest
static void testBeforeInsertSetsIndustry() {
List<Account> accounts = new List<Account>{
new Account(Name = 'Test 1', Industry = null),
new Account(Name = 'Test 2', Industry = 'Agriculture')
};
Test.startTest();
insert accounts;
Test.stopTest();
Map<Id, Account> result = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accounts]);
System.assertEquals('Other', result.get(accounts[0].Id).Industry, 'Null industry should default to Other.');
System.assertEquals('Agriculture', result.get(accounts[1].Id).Industry, 'Existing industry should not be overwritten.');
}
@isTest
static void testAfterInsertCreatesTasks() {
Account first = new Account(Name = 'First Corp');
Account second = new Account(Name = 'Second Corp');
Test.startTest();
insert new List<Account>{ first, second };
Test.stopTest();
Set<Id> accountIds = new Set<Id>{ first.Id, second.Id };
Map<Id, Integer> taskCounts = new Map<Id, Integer>();
for (Task task : [SELECT WhatId FROM Task WHERE WhatId IN :accountIds]) {
Integer count = taskCounts.containsKey(task.WhatId) ? taskCounts.get(task.WhatId) : 0;
taskCounts.put(task.WhatId, count + 1);
}
System.assertEquals(1, taskCounts.get(first.Id), 'First account should have one task.');
System.assertEquals(1, taskCounts.get(second.Id), 'Second account should have one task.');
}
@isTest
static void testBulkInsert200Records() {
List<Account> bulkAccounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
bulkAccounts.add(new Account(Name = 'Bulk ' + i, NumberOfEmployees = 1200));
}
Test.startTest();
insert bulkAccounts;
Test.stopTest();
System.assertEquals(200, [SELECT COUNT() FROM Task WHERE WhatId IN :bulkAccounts],
'Should create 200 tasks for bulkAccounts accounts.');
}
@isTest
static void testBeforeDeletePrevention() {
Account acc = new Account(Name = 'Big Corp', NumberOfEmployees = 200);
insert acc;
Test.startTest();
Database.DeleteResult result = Database.delete(acc, false);
Test.stopTest();
System.Assert.isFalse(result.isSuccess(), 'Delete should fail for large account.');
System.assert(result.getErrors()[0].getMessage().contains('Cannot delete accounts with more than 100 employees.'));
}
@isTest
static void testAddressSyncOnStateChange() {
Account acc = new Account(Name = 'Address Test', BillingCity = 'Boston',
BillingState = 'MA', BillingCountry = 'US');
insert acc;
Contact contact = new Contact(LastName = 'Test', AccountId = acc.Id);
insert contact;
Test.startTest();
acc.BillingState = 'NY';
update acc;
Test.stopTest();
Contact saved = [SELECT MailingCity, MailingState, MailingCountry
FROM Contact WHERE Id = :contact.Id];
System.assertEquals('Boston', saved.MailingCity);
System.assertEquals('NY', saved.MailingState);
System.assertEquals('US', saved.MailingCountry);
}
}
7. Advanced Trigger Concepts
Asynchronous Processing
Use asynchronous Apex when its execution model and limits suit the work, such as deferred callouts or eligible CPU-intensive processing. Execution is eventual, and some limits remain unchanged, so splitting work into asynchronous jobs does not remove every limit.
@futuremethods: Suitable for simple deferred tasks such as callouts. Pass IDs rather than sObjects and query inside the method. The per-transaction limit is 50 future calls in synchronous and Queueable contexts, and zero in Batch and future contexts.- Queueable Apex: Accepts sObjects as parameters and supports chaining. A running job can enqueue one child; chain depth is generally unlimited, subject to edition and configured exceptions. The enqueue limit is 50 in a synchronous transaction and one in an asynchronous transaction.
- Batch Apex: Designed for processing millions of records that exceed synchronous limits.
public class ExternalSyncService {
@future(callout=true)
public static void syncAccountDetails(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Name, Website, Phone FROM Account WHERE Id IN :accountIds];
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('callout:External_CRM/sync');
req.setHeader('Content-Type', 'application/json');
List<Map<String, Object>> payload = new List<Map<String, Object>>();
for (Account acc : accounts) {
payload.add(new Map<String, Object>{
'sfId' => acc.Id,
'name' => acc.Name,
'website' => acc.Website,
'phone' => acc.Phone
});
}
req.setBody(JSON.serialize(payload));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
throw new SyncException('Sync failed with HTTP status ' + res.getStatusCode());
}
}
public class SyncException extends Exception {
}
}
public class AccountRevenueCalculator implements Queueable {
private List<Account> accounts;
public AccountRevenueCalculator(List<Account> accounts) {
this.accounts = accounts;
}
public void execute(QueueableContext context) {
Set<Id> accountIds = new Map<Id, Account>(accounts).keySet();
// Single SOQL outside the loop — bulkified
Map<Id, Decimal> revenueMap = new Map<Id, Decimal>();
for (Opportunity opp : [
SELECT AccountId, Amount FROM Opportunity
WHERE AccountId IN :accountIds AND StageName = 'Closed Won'
]) {
if (opp.Amount != null) {
Decimal prev = revenueMap.containsKey(opp.AccountId) ? revenueMap.get(opp.AccountId) : 0;
revenueMap.put(opp.AccountId, prev + opp.Amount);
}
}
List<Account> toUpdate = new List<Account>();
for (Account acc : accounts) {
Decimal revenue = revenueMap.containsKey(acc.Id) ? revenueMap.get(acc.Id) : 0;
toUpdate.add(new Account(Id = acc.Id, AnnualRevenue = revenue));
}
if (!toUpdate.isEmpty()) update toUpdate;
}
}
// Enqueue from handler (onAfterInsert):
// System.enqueueJob(new AccountRevenueCalculator(eligibleAccounts));
How do you make and test reliable callouts?
Use a Named Credential and its associated authentication configuration to keep endpoints and credentials out of Apex. The preceding example requires a Named Credential named External_CRM. Treat failed responses and callout exceptions as failures, and design a monitored retry process for transient errors. Give each logical operation an idempotency key that the receiving service can use to avoid duplicate effects when requests are retried. In tests, register an HttpCalloutMock with Test.setMock, exercise the enqueueing code between Test.startTest() and Test.stopTest(), and assert the observable outcome after asynchronous work runs. Cover both success and failure responses.
Utility Helper Classes
Create small, reusable utility classes for common tasks — email sending, logging, validation, data transformation. This keeps your handler class focused and your code modular.
public class CustomEmailService {
public static void sendSingleEmail(String recipientEmail, String subject, String body) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new List<String>{ recipientEmail });
mail.setSubject(subject);
mail.setPlainTextBody(body);
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{ mail });
}
}
8. Conclusion & Next Steps
You've now covered Apex trigger events, context variables, handler patterns, recursion, testing, and asynchronous processing. Choose Flow or Apex according to the requirements and the behavior of the complete automation.
Key Takeaways
- Choose the Right Tool: Select Flow or Apex based on the requirements, and migrate legacy automation to Flow.
- One Trigger Per Object: Delegate logic to a Trigger Handler class — keep the trigger file as a thin dispatcher.
- Bulkify Everything: Never put SOQL or DML inside loops. Handle collections in a single operation.
- Handle Recursion: Prefer idempotent change-based logic and scope any necessary guard to the operation and records.
- Test Thoroughly: Cover positive, negative, and bulk scenarios, and meet the coverage requirement for the selected deployment test level.
- Use Async Deliberately: Choose
@future, Queueable, or Batch Apex when its limits and eventual execution suit the work. - Build Utility Classes: Keep handler classes lean with reusable email, logging, and validation utilities.
Practice Exercises
- Contact Name Normalization:
before insert/before updateon Contact — ensure FirstName and LastName are stored in Proper Case. Add error if LastName is blank. - Account → Contact Address Sync:
after updateon Account — when BillingAddress changes, update MailingAddress on all related Contacts. Must be bulkified. - Case Deletion Prevention:
before deleteon Case — prevent deletion if Status is 'Closed' or 'Escalated'. - Opportunity Stage Rollup: On Opportunity
after insert/after update— when moved to 'Closed Won', update a custom fieldLast_Won_Opportunity_Date__con the related Account. - External Data Sync (Advanced):
after insert/after updateon a custom object — when a field changes to 'Approved', make an async callout to an external API. Handle callout errors.
Recommended Resources
- Salesforce Apex Developer Guide: Apex Triggers
- Trailhead: Apex Triggers Module
- Search "Salesforce Trigger Framework" on GitHub for open-source community frameworks.
Frequently asked questions
What is the difference between a before and an after trigger?
A before trigger runs before the record is saved, so you can change field values on Trigger.new directly with no DML. An after trigger runs once the record is saved, so record Ids and system fields are available and you can create or update related records. Records in Trigger.new are read-only in after triggers.
Which context variables are available in a before insert trigger?
Trigger.new is available and editable. Trigger.newMap is null because the records have no Ids yet, and Trigger.old and Trigger.oldMap are not available on insert. Trigger.isInsert, Trigger.isBefore and Trigger.operationType are set.
How do you stop a recursive trigger in Salesforce?
Keep a static Set
Can an Apex trigger make a callout?
Not directly, because a trigger can't make a synchronous callout. Enqueue a Queueable class that implements Database.AllowsCallouts, or call an @future(callout=true) method, and make the callout there.
What is the difference between Trigger.new and Trigger.old?
Trigger.new holds the new versions of the records and is available in insert, update and undelete triggers. Trigger.old holds the previous versions and is available in update and delete triggers. Use Trigger.oldMap.get(record.Id) to compare a field before and after an update.
How many records does a trigger process at once?
Apex triggers receive records in chunks of 200. Platform event and Change Data Capture triggers receive up to 2,000 events per batch.
Should I use an Apex trigger or a record-triggered flow?
Use a record-triggered flow for straightforward field updates and actions that admins should be able to maintain. Use an Apex trigger for complex logic, high data volumes, detailed error handling or anything that needs unit tests with full control. Avoid having both a trigger and several flows changing the same fields on one object.
Sources: Apex Developer Guide: Triggers · Trigger context variables · Execution governors and limits