Learn Salesforce Anywhere Anytime

Theme Switch

Apex Trigger


A Salesforce Apex Trigger is a piece of code that executes before or after specific events occur on a Salesforce object, such as record insertion, update, deletion, or undeletion. Triggers are used to automate business processes, enforce data integrity, and perform actions based on certain conditions. Here’s an example of a basic Apex Trigger:

trigger MyTrigger on Account (before insert) {
    for (Account acc : {
        // Trigger logic goes here
        // Example: Set a default value for a field
        acc.Description = 'Default Description';

In this example:

  • trigger MyTrigger declares the trigger named “MyTrigger” on the “Account” object.
  • (before insert) specifies that the trigger should run before the insertion of Account records.
  • for (Account acc : is a loop that iterates through the records being inserted (stored in
  • Inside the loop, you can include the desired trigger logic. In this case, we’re setting a default value for the “Description” field of each Account being inserted.

Here are a few key points about Apex Triggers:

  1. Events: Triggers can be defined to execute before or after specific events, such as before insert, after update, before delete, etc. Multiple triggers can be created for the same object and event.
  2. Trigger Context Variables: Salesforce provides trigger context variables, such as, Trigger.old, and Trigger.isBefore, which allow access to the records involved in the trigger and provide information about the context of the trigger execution.
  3. Bulk Processing: Triggers are designed to handle bulk operations, meaning they can process multiple records simultaneously. The code inside a trigger should be written to handle scenarios where a trigger is invoked with multiple records at once.
  4. DML Operations: Triggers can perform additional data manipulation using Data Manipulation Language (DML) statements like insert, update, delete, and undelete. However, it’s important to consider governor limits and bulkification techniques when performing DML operations inside a trigger.
  5. Context-specific Triggers: Triggers can be created for specific contexts, such as before insert, after update, or after undelete. Each context has its own set of trigger events, context variables, and considerations.

Apex Triggers are a powerful tool for automating processes and implementing business logic within the Salesforce platform. They allow you to respond to data changes and perform custom actions to meet specific requirements.