Apex Trigger Cheat Sheet — Master Triggers in Salesforce (2025)

Published On: November 8, 2025

🔍 Introduction

In the Salesforce world, Apex Triggers are the backbone of automation at the database level.
They allow developers to perform actions before or after data manipulation events such as insert, update, or delete.

Whether you’re preparing for Salesforce Developer interviews, building real-time automation, or migrating logic from Flows to code — mastering Apex Triggers is a must-have skill in 2025.

In this post, you’ll learn everything you need to know — from syntax to best practices — plus real-world examples and interview-ready insights.


⚙️ What Is an Apex Trigger?

An Apex Trigger is a piece of code that executes automatically in response to a specific event on a Salesforce object.

In simpler words:

“A trigger is like a workflow rule — but written in Apex and with much more power and flexibility.”


🔁 Trigger Events in Salesforce

Triggers can fire before or after certain database operations.
Here’s a quick reference table 👇

Trigger EventWhen It ExecutesCommon Use Case
before insertBefore the record is insertedModify field values before saving
before updateBefore the record is updatedPrevent invalid field updates
before deleteBefore the record is deletedRestrict deletion based on logic
after insertAfter record is insertedCreate related records automatically
after updateAfter record is updatedUpdate related objects
after deleteAfter record is deletedCleanup or cascade deletions
after undeleteAfter record is restored from Recycle BinRecreate relationships

🧩 Basic Trigger Syntax

Here’s how a basic trigger looks in Apex:

trigger AccountTrigger on Account (before insert, after update) {
    if(Trigger.isBefore && Trigger.isInsert){
        // Logic before account insert
    }
    if(Trigger.isAfter && Trigger.isUpdate){
        // Logic after account update
    }
}

Trigger Context Variables

Context variables provide access to records and trigger state information during execution.

VariableDescription
Trigger.newList of new records
Trigger.oldList of old records
Trigger.newMapMap<Id, new record>
Trigger.oldMapMap<Id, old record>
Trigger.isBefore / Trigger.isAfterIdentifies trigger timing
Trigger.isInsert, Trigger.isUpdate, etc.Identifies event type
Trigger.sizeNumber of records in the trigger context

💡 Real-Time Example: Auto Create Task on Opportunity Closed Won

Scenario:
Whenever an Opportunity is marked Closed Won, we want to automatically create a follow-up Task for the sales rep.

trigger OpportunityTrigger on Opportunity (after update) {
    List<Task> taskList = new List<Task>();
    for(Opportunity opp : Trigger.new){
        if(opp.StageName == 'Closed Won' &&
           Trigger.oldMap.get(opp.Id).StageName != 'Closed Won'){
            taskList.add(new Task(
                Subject = 'Follow up with customer',
                WhatId = opp.Id,
                Status = 'Not Started',
                Priority = 'High'
            ));
        }
    }
    if(!taskList.isEmpty())
        insert taskList;
}

✅ This is a common real-time use case asked in interviews.


🧠 Apex Trigger Best Practices (2025 Edition)

Following best practices keeps your org efficient, scalable, and error-free.

1. One Trigger Per Object

Keep logic separated into handler classes to avoid confusion and ensure maintainability.

2. Bulkify Everything

Always assume multiple records.
Avoid using DML or SOQL inside for loops.

3. Use Collections

Work with List, Set, and Map for efficiency.

4. Handle Recursion

Use static variables or frameworks to prevent infinite loops.

5. Use Context Variables

They help control flow and avoid repetitive logic.

6. Write Unit Tests

Ensure ≥75% code coverage and verify business logic using System.assert().

7. Async Apex for Post-Processing

Move heavy operations to @future, Queueable, or Batch Apex.


🧱 Trigger Framework Example (Handler Pattern)

A clean and modular way to organize triggers:

trigger AccountTrigger on Account (before insert, after update) {
    AccountTriggerHandler handler = new AccountTriggerHandler();
    if(Trigger.isBefore && Trigger.isInsert)
        handler.beforeInsert(Trigger.new);
    if(Trigger.isAfter && Trigger.isUpdate)
        handler.afterUpdate(Trigger.new, Trigger.oldMap);
}

Handler Class:

public class AccountTriggerHandler {
    public void beforeInsert(List<Account> accList){
        for(Account acc : accList){
            acc.Description = 'Created via Trigger';
        }
    }
    public void afterUpdate(List<Account> newList, Map<Id, Account> oldMap){
        // Additional post-update logic here
    }
}

✅ Makes testing, debugging, and maintenance much easier.


🧪 Test Class Example

Writing proper test classes ensures code quality and deployment readiness.

@isTest
private class AccountTriggerTest {
    @isTest static void testBeforeInsert() {
        Account acc = new Account(Name='Test Account');
        insert acc;

        Account inserted = [SELECT Description FROM Account WHERE Id=:acc.Id];
        System.assertEquals('Created via Trigger', inserted.Description);
    }
}

🧾 Common Interview Scenarios

ScenarioWhat It Tests
Prevent duplicate recordsSOQL + Validation logic
Auto-create child recordsAfter Insert
Prevent recursive updatesStatic variable handling
Update related recordsAfter Update
Async operationsFuture / Queueable Apex
Cascade deleteAfter Delete

🔍 Real-World Tip

If your Trigger logic feels too large — it probably belongs in a Handler class.
Keep your Trigger thin, your logic modular, and your code bulkified.


🧭 Key Takeaways

  • Use one trigger per object
  • Keep triggers bulk-safe and modular
  • Always write unit tests
  • Use async methods for complex post-DML logic
  • Learn to debug recursion and context behavior

📚 Bonus: Interview & Project Resources

🔥 Practice with real recruiter-level questions:
👉 Salesforce Interview Mega-Pack — 1000+ Real Questions & Answers

🚀 Build end-to-end Salesforce Projects (with LWC + Trigger + Flow):
👉 Sales Cloud Project for Developers — Hands-On Implementation


🏁 Conclusion

Mastering Apex Triggers isn’t just about syntax — it’s about writing scalable, maintainable, and efficient automation logic.

With the right framework, bulkification strategy, and testing habits, you’ll not only ace interviews but also handle complex enterprise implementations like a pro.

TrailheadTitans

At TrailheadTitans.com, we are dedicated to paving the way for both freshers and experienced professionals in the dynamic world of Salesforce. Founded by Abhishek Kumar Singh, a seasoned professional with a rich background in various IT companies, our platform aims to be the go-to destination for job seekers seeking the latest opportunities and valuable resources.

Related Post

Leave a Comment