Trigger Context Variable in Salesforce Apex : Bijay Kumar

Trigger Context Variable in Salesforce Apex
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



**Summary of Trigger Context Variables in Salesforce Apex** In Salesforce, automation processes are handled using **Flows** and **Triggers**. Flows are suitable for simpler tasks, while **Apex Triggers** are used for more complex automation, allowing actions based on record changes like creation, update, or deletion. ### Key Details: 1. **Trigger Context Variables**: These are built-in variables that help define the context in which a trigger runs. They include: - `Trigger.new`: New versions of records being inserted or updated. - `Trigger.old`: Old versions of records being updated or deleted. - `Trigger.newMap` and `Trigger.oldMap`: Maps of record IDs to their new or old versions. - `Trigger.isInsert`, `Trigger.isUpdate`, `Trigger.isDelete`: Boolean checks for the operation type. - `Trigger.isBefore` and `Trigger.isAfter`: Checks if the trigger runs before or after the record is saved. 2. **Examples**: - Using `Trigger.new` to set default values before inserting a record. - Using `Trigger.old` to prevent changes to specific fields during updates. - Using `Trigger.newMap` to update related records based on changes in the main record. 3. **Use Cases**: Triggers can automate various processes such as: - Automatically assigning default values. - Preventing deletion of records with dependencies. - Sending emails after a record is created. ### Conclusion Understanding these context variables is essential for effectively using Apex triggers in Salesforce. They provide the necessary tools to create robust automation processes tailored to your business needs. ### Additional Information: - Apex triggers help maintain data integrity and automate repetitive tasks. - Best practices include keeping triggers focused on a single task and avoiding complex logic within them. **Hashtags for SEO**: #Salesforce #ApexTriggers #Automation #SalesforceDevelopment #TriggerContextVariables #SalesforceApex #CRM #DataIntegrity #SalesforceTutorials #SalesforceTips


In Salesforce, we use Flows and Triggers to automate any process. To define when the flow should be executed, we can select the flow execution condition, such as record creation, update, deletion, etc.

If you have a complex process and want to automate it, you need to use the Apex trigger. Here, also, we need to define the condition under which this trigger should be executed. We use the trigger context variables to determine the condition in an Apex trigger.

In this tutorial, we will learn about the trigger context variable in Salesforce Apex. I will explain different context variables and how to use them in an Apex trigger to automate the process.

Trigger Context Variable in Salesforce Apex

When we write a trigger in Salesforce Apex, it runs automatically when something happens to a record, like insert, update, or delete.

Salesforce provides special built-in variables called trigger context variables to help us define when the trigger should start to execute or automate the process. These variables help us understand the context or situation in which the trigger is running.

Types of context variables in the Salesforce trigger:

  1. Trigger.new: Returns a list of the recently created records of the sObject records (available for insert, update, and undelete triggers).
  2. Trigger.old: Returns a list of the old records that are already available in Salesforce objects (available for update and delete triggers).
  3. Trigger.newMap: A map of IDs to the new versions of the sObject records.
  4. Trigger.oldMap: A map of IDs to the old versions of the sObject records.
  5. Trigger.isInsert: Returns true if the trigger is fired due to an insert operation.
  6. Trigger.isUpdate: Returns true if the trigger is fired due to an update operation.
  7. Trigger.isDelete: Returns true if the trigger is fired due to a delete operation.
  8. Trigger.isBefore: Returns true if the trigger is fired before the record is saved.
  9. Trigger.isAfter: Returns true if the trigger is fired after the record is saved.

Use Context Variables in Apex Trigger Code

Below, I will explain each type of trigger context variable and how we can use them in trigger code to specify when the trigger should execute to automate the process.

1. Trigger.new Context Variable in Apex Trigger

The Trigger.new context variable contains a list of new versions of the records that are being inserted or updated. It’s available before insert, before update, after insert, and after update triggers.

Example:

For example, whenever I create an account record, the other fields where I want to set default values should be automatically saved. I will explain how to do that in the Apex code below.

]Here, I’m using the before insert trigger event because we are creating a record for the same object. Then, in each loop, we declare Trigger.new, which returns the list of records on which we are trying to perform a DML operation.

In the for loop, I assigned some values to the account fields so that when we create the account record and don’t fill these fields after creating the records, the value we assigned will get automatically added to the record.

trigger AccountTrigger on Account (before insert) {
       for (Account acc: Trigger.new) {
           acc.Active__c = 'Active';
           acc.Rating = 'Hot';
      }
}

I only filled out the account name field and saved the record directly.

Trigger.new in Salesforce Apex

When you save the record and open the account details, the values we assigned in the Apex trigger code are displayed in the account details.

Trigger Context Variable in Salesforce Apex

2. Trigger.old Context Variable in Apex Trigger

In Salesforce, Trigger.old holds the previous versions of records that are being updated or deleted. This is useful when comparing old and new values during a trigger operation.

You can access Trigger.old in the following trigger events: before update, after update, before delete, and after delete.

Example:

For example, if you set the account status, you don’t want to change that status by any other user.

Even if it is editable, you can use trigger.old to fetch the existing account status and check with the new status. If it does not match, restrict the record from being saved.

trigger TriggerDemo on Account(before insert) {
    
   for ( Account oldAcc: Trigger.old ) {
        for ( Account newAcc: Trigger.new ) {
            if ( oldAcc.Id == newAcc.Id && oldAcc.Active__c != newAcc.Active__c ) {
                newAcc.Active__c.addError( 'Amount cannot be changed' );
            }
        }
    } 
}

3. Trigger.newMap Context Variable in Apex Trigger

In Salesforce triggers, the Trigger.newMap is a map of record IDs to the new versions of the records. It is available in before insert, before update, after insert, and after update triggers.

This map allows us to easily access records by their IDs, making it useful when you need to retrieve a specific record based on its unique identifier.

Example:

For example, we want to update the mailing city of the contact records whenever we update the billing city related to the account records.

In the Apex trigger code below, I created a trigger on the account object and used it after the update event because we are updating the related object’s record.

Then, I initiated a map with ID as key and sObject Account and assigned it as a newMap. After that, I created a list in which I fetched contacts using the KeySet so it would get contacts from the contact object, which is associated with the account present in the Trigger.newMap.

Then, I added for each loop and passed the list of contacts that we fetched to the contact object instance.

After that, create an account sObject, which will store an account record associated with the contact. Then, assign the account billing city to the contact mailing city and simply update the contact list.

trigger TriggerDemo on Account(after update) {
        
    Map<Id,Account> nMap = new Map<Id,Account>();
    nMap = Trigger.newMap;
    List<Contact> cList = [ SELECT LastName, AccountId FROM Contact WHERE AccountId IN: nMap.keySet() ];
    
    for (Contact c : cList) {
            Account a = nMap.get(c.AccountId);
            c.MailingCity= a.BillingCity;
        }
    update cList;
}

Now navigate to the account records with an associate contact, update the billing city, and save the record.

Apex Triggers in Salesforce

As you can see in the first image, the mailing address is null. However, if you update the billing address on the account, that address will appear in the mailing address.

Create Trigger in Salesforce Apex

4. Trigger.oldMap Context Variable in Apex Trigger

The Trigger.oldMap is a map that stores records’ IDs and previous versions before they are updated or deleted. It’s available in triggers that run before, after, before, and after updates.

You can use it to compare the old and new values of records during an update or to access deleted records by their ID in delete triggers. This is useful for tracking changes or performing actions based on how a record was before the current operation.

Example:

For example, if you set the opportunity amount, you don’t want to change that amount by any other user. Even if it is editable, you can use trigger.oldMap to fetch the existing opportunity amount and check it against the new amount. If it does not match, then restrict the record from getting saved.

Here, we created a trigger on the opportunity object, and the event we created was before update event. Then I initiated map with ID as key and sObject opportunity and assigned it as a oldMap.

Then, I added for each loop and passed the Trigger.new, which stores the new value that the user is going to update in the amount field.

In the for loop, I created the oldOpp variable, which stores the record of new opportunities that we fetched using the get() method.

Then, the if condition is added, checking whether the new opportunity amount equals the old opportunity. If not, we use the addError() method to throw an error message and restrict the record from being saved.

trigger OppoTrigger on Opportunity (before update) {
    
    Map<Id, Opportunity> oppoMap = Trigger.oldMap;

        for ( Opportunity newOpp : Trigger.new ) {
                Opportunity oldOpp = oppoMap.get ( newOpp.Id );
                      if ( newOpp.Amount != oldOpp.Amount ) {
                            newOpp.Amount.addError ( 'Amount cannot be changed' );
                      }
           }
}

As you navigate to the opportunity record, you can see the number fields with the value of 4400.

Create an Apex Trigger in Salesforce

As I changed the value and tried to save the record, the error showed that we passed in the addError method, and the record was not saved.

Apex Triggers in Salesforce

So, these are some important context variables in Apex Trigger in Salesforce.

5. Trigger.isInsert Context Variable in Apex Trigger

In Salesforce, Trigger.isInsert is a context variable used within Apex triggers to check if the trigger was executed due to a record insertion (i.e., when records are being created).

It returns true only when the trigger events are:

  • Before Insert
  • After Insert

Example:

If you want to automatically add a default description to new case records only when they are inserted, but not when they are updated.

Here, we created a trigger on the case object, and the event we created was before insert event. Then, in the if condition, using the Trigger.isInsert context variable, we checked only if the record is being created; then, only this trigger should get executed.

Then again, in the if condition, we checked if the description field is black on the new record and then added the default description that we provided.

trigger ContextVariable on Case (before insert) {

    if (Trigger.isInsert) {
        for (Case c : Trigger.new) {
            if (String.isBlank(c.Description)) {
                c.Description = 'This is a newly created case.  Description not provided.';
            }
        }
    }
}

While creating the new record on the case object here, I left the description field blank and saved the record.

Trigger.isInsert Context Variable in Salesforce Trigger

After the record is created, you can see in the description field that the value is populated.

Trigger.isInsert Context Variable in Trigger

6. Trigger.isUpdate Context Variable in Apex Trigger

In Salesforce Apex, the Trigger.isUpdate context variable checks whether the trigger is executed due to an update operation (like when a user edits a record).

We can use Trigger.isUpdate in trigger code to differentiate between different trigger events, such as insert, update, delete, etc., so we can write logic specific to each case.

Example:

If you want to check if the existing account name was changed, then update the custom checkbox field Name_Changed__c, which automatically sets it to true.

Before creating the trigger in the image below, you can see the account name value. Also, the name changed checkbox field is not checked (not true).

Trigger.isUpdate Context Variable in Apex Trigger

In the Apex trigger code below, we used the before update trigger event. Then, in the if condition, using the Trigger.isUpdate context variable, we checked only if the record is being updated; then, only this trigger should get executed.

Then, the Trigger.new.size() returns the total number of records being updated. Using Trigger.new[] and Trigger.old[], we checked if the new value of the name field does not match the old value, changed it, and set the checkbox field to checked (true).

trigger AccountTrigger on Account (before update) {

    if (Trigger.isUpdate) {
          for (Integer i = 0; i < Trigger.new.size(); i++) {
                  Account newAcc = Trigger.new[i]; 
                  Account oldAcc = Trigger.old[i];

            if (newAcc.Name != oldAcc.Name) {
                   newAcc.Name_Changed__c = true;
            }  
        }
    }
}

After the record is updated, the ‘name changed’ field is automatically set to true, meaning we changed the account name.

Trigger.isUpdate Context Variable

7. Trigger.isDelete Context Variable in Apex Trigger

The Trigger.isDelete context variable checks whether the trigger is executed due to a delete operation, either a single or bulk record delete.

It is used inside a trigger to determine whether the operation is a DELETE event, such as:

  • before delete
  • after delete

Example:

For example, you want to prevent the deletion of an Account if they have related opportunities.

In the image below, you can see that for the ‘Edge Communications’ account, we have four related opportunities. We need to create a trigger so that whenever a user tries to delete the account, it should not be deleted.

Trigger.isDelete Context Variable in Apex Trigger

Here, we need to use the before delete trigger event because we want to prevent the deletion of an Account if it has related opportunities.

Using the Trigger.isDelete context variable, we checked only if the record is being updated; then, only this trigger should get executed. The Set Collection is used to store unique values. Here, we are storing existing account IDs.

Then, we checked the accounts to see if there was any related opportunity. If there was one, we displayed the error using the addError() method and prevented the account deletion.

trigger AccTrigger on Account (before delete) {
    
    if (Trigger.isDelete) {
          Set<Id> accountIds = new Set<Id>();

        for (Account acc : Trigger.old) {
                accountIds.add(acc.Id);
        }

        Set<Id> accountIdsWithOpps = new Set<Id>();
        for (Opportunity opp : [SELECT Id, AccountId FROM Opportunity WHERE AccountId IN :accountIds]) {
            accountIdsWithOpps.add(opp.AccountId);
        }

        for (Account acc : Trigger.old) {
            if (accountIdsWithOpps.contains(acc.Id)) {
                acc.addError('You cannot delete this account because it has related Opportunities.');
            }
        }
    }
}

Here we are deleting this account, which has related opportunities.

Trigger.isDelete Context Variable

We got the error that we provided in the addError() method in the Apex trigger code.

AddError in Salesforce Apex

8. Trigger.isBefore Context Variable in Apex Trigger

The Trigger.isBefore context variable in Apex Trigger is used to check whether a trigger is executing before the records are saved to the database. This is important because:

  • In a before trigger, you can modify the record values directly before they’re saved.
  • It’s commonly used for validation or automatic field updates.

The Trigger.isBefore context variable in Apex checks whether a trigger is executing before the records are saved to the database. This is important because:

  • In a before trigger, you can modify the record values directly before they’re saved.
  • It’s commonly used for validation or automatic field updates.

We can use Trigger.isBefore when you want to:

  • Set field values to fields before insert or update.
  • Perform validation checks and throw errors if conditions aren’t met.
  • Avoid making a DML operation inside the trigger (you can modify Trigger.new directly).

Example:

Suppose you want to automatically set a default value for a custom field ‘Status__c’ on the contact object before inserting a record. Also, when you update ‘Email’ from the existing contact record again, the ‘Status__c’ field is set to ‘Email Changed’.

As we saw, we can use Trigger.isBefore for before insert and update trigger events, and in our example, before update is also required.

After that, using the Trigger.isBefore context variable, we checked whether a trigger is executing before the records are saved to the database.

First, we wrote logic for the isInsert operation and then for the isUpdate operation.

trigger ContactTrigger on Contact (before insert, before update) {
    
    if (Trigger.isBefore) {
        if (Trigger.isInsert) {
            for (Contact con : Trigger.new) {
                if (con.Status__c == null) {
                    con.Status__c = 'New';
                }
            }
        }

        if (Trigger.isUpdate) {
            for (Contact con : Trigger.new) {
                if (con.Email != Trigger.oldMap.get(con.Id).Email) {
                    con.Status__c = 'Email Changed';
                }
            }
        }
    }
}

Here, I’m creating a new contact record, leaving the ‘Status’ field blank. Now, let’s see what happens when I save this record.

isInsert Operation in Salesforce Apex Trigger

As I save this record, you can see in the ‘Status’ field that the value is populated as provided in the trigger.

Trigger Events in Salesforce Apex

Now I’m updating the email field on the same record; this time, the status field is the same.

Edit Contact Records in Salesforce

The ‘Status’ field’s value changes as I save the record.

IsBefore in Salesforce Apex Trigger

9. Trigger.isAfter Context Variable in Apex Trigger

Trigger.isAfter is a context variable in Apex triggers that checks whether the trigger is executed after a record is saved to the database.

It is used when you want to perform operations after the data has been committed, such as:

  • Sending emails.
  • Creating related records.
  • Calling future methods or queueable Apex.

Example:

You want to automate the process of sending an email when a new account record is created. Here we need to use the isAfter context variable because this action should happen after creating the record or after data has been committed.

First, we need to create an Apex class where we will develop a future method to send an email to the email address on the account record.

public class WelcomeEmailSender {
    @future
    public static void sendWelcomeEmail(Id accountId) {
        Account acc = [SELECT Name, Email__c FROM Account WHERE Id = :accountId LIMIT 1];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] { acc.Email__c });
        mail.setSubject('Welcome to Our Company');
        mail.setPlainTextBody('Hello ' + acc.Name + ', welcome!');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

Now we will write a trigger on the account object and call the future method class in this trigger.

trigger AccTrigger on Account (after insert) {
    
    if (Trigger.isAfter && Trigger.isInsert) {
        for (Account acc : Trigger.new) {

            WelcomeEmailSender.sendWelcomeEmail(acc.Id);
        }
    }
}

Here you can see I’m creating a new account record.

Trigger.isAfter Context Variable in Apex Trigger

As the account gets inserted into the Salesforce database, Salesforce sends the email to the customer’s email address that they provided.

IsAfter Operation in Salesforce Apex Trigger

Conclusion

I hope you have an idea about the trigger context variable in Salesforce Apex. I have explained different context variables and how to use them in an Apex trigger to automate the process with an example and step-by-step explanation.

You may like to read:

The post Trigger Context Variable in Salesforce Apex appeared first on SalesForce FAQs.


May 16, 2025 at 07:00PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce