Skip to main content
SFDC Developers
Apex

Getting Started with Apex Triggers in Salesforce

Vinay Vernekar · · 2 min read

Getting Started with Apex Triggers in Salesforce

Apex triggers are one of the most powerful tools in a Salesforce developer’s toolkit. They allow you to execute custom code before or after DML operations on Salesforce records.

What is an Apex Trigger?

An Apex trigger is a piece of code that executes before or after specific data manipulation language (DML) events occur, such as before records are inserted into the database or after records are deleted.

Trigger Syntax

trigger TriggerName on ObjectName (trigger_events) {
    // code_block
}

Trigger Context Variables

Salesforce provides several context variables that give you access to the records being processed:

  • Trigger.new - Returns a list of the new versions of the sObject records
  • Trigger.old - Returns a list of the old versions of the sObject records
  • Trigger.isInsert - Returns true if the trigger was fired due to an insert operation
  • Trigger.isUpdate - Returns true if the trigger was fired due to an update operation
  • Trigger.isDelete - Returns true if the trigger was fired due to a delete operation

Best Practices

  1. One trigger per object - Consolidate all logic into a single trigger per object
  2. Use trigger handlers - Move logic out of the trigger into a handler class
  3. Bulkify your code - Always handle collections, not single records
  4. Avoid SOQL in loops - Query outside of loops to stay within governor limits

Example: Account Trigger

trigger AccountTrigger on Account (before insert, before update) {
    AccountTriggerHandler handler = new AccountTriggerHandler();

    if (Trigger.isInsert) {
        handler.onBeforeInsert(Trigger.new);
    } else if (Trigger.isUpdate) {
        handler.onBeforeUpdate(Trigger.new, Trigger.oldMap);
    }
}

Conclusion

Apex triggers are essential for any Salesforce developer. By following best practices and understanding the trigger context, you can build robust and efficient automation for your Salesforce org.

Share this article

Vinay Vernekar

Vinay Vernekar

Salesforce Developer & Founder

Vinay is a seasoned Salesforce developer with over a decade of experience building enterprise solutions on the Salesforce platform. He founded SFDCDevelopers.com to share practical tutorials, best practices, and career guidance with the global Salesforce community.

Comments

Loading comments...

Leave a Comment

Trending Now
Check back soon for trending Salesforce developer content