In Salesforce, we use Flows and Triggers to automate any process. To define when the flow should execute, we can select a flow execution condition, such as record creation, update, or deletion.
If you have a complex process and want to automate it, you should use an 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 whenever something happens to a record, such as an insert, update, or delete.
Salesforce provides built-in variables called trigger context variables to help us define when a trigger should start executing or automating a process. These variables help us understand the context or situation in which the trigger is running.
Types of context variables in the Salesforce trigger:
- Trigger.new: Returns a list of the recently created records of the sObject records (available for insert, update, and undelete triggers).
- Trigger.old: Returns a list of the old records that are already available in Salesforce objects (available for update and delete triggers).
- Trigger.newMap: A map of IDs to the new versions of the sObject records.
- Trigger.oldMap: A map of IDs to the old versions of the sObject records.
- Trigger.isInsert: Returns true if the trigger is fired due to an insert operation.
- Trigger.isUpdate: Returns true if the trigger is fired due to an update operation.
- Trigger.isDelete: Returns true if the trigger is fired due to a delete operation.
- Trigger.isBefore: Returns true if the trigger is fired before the record is saved.
- 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 values to the account fields so that when we create the account record and don’t fill these fields, the values we assigned will be 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.

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

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 any other user to change it.
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-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 created a map with ID as the key and sObject Account as the value, and assigned it to newMap. After that, I created a list and fetched contacts using the KeySet to get the contacts from the contact object associated with the account in Trigger.newMap.
Then, I added for each loop and passed the list of contacts we fetched to the contact object instance.
After that, create an account sObject that stores the 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.

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.

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 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 a record’s state before the current operation.
Example:
For example, if you set the opportunity amount, you don’t want another user to change it. 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, prevent the record from being saved.
Here, we created a trigger on the opportunity object, and the event we created was a before update event. Then I created a map with ID as the key and sObject opportunity as the value, and assigned it to 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 to store the records of new opportunities we fetched using the get() method.
Then, an if condition is added to check whether the new opportunity amount equals the old one. 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.

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

So, these are some important context variables in an Apex Trigger in Salesforce.
5. Trigger.isInsert Context Variable in Apex Trigger
In Salesforce, Trigger.isInsert is a context variable used in Apex triggers to determine whether the trigger was executed because a record was inserted (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 a before-insert event. Then, in the if condition, using the Trigger.isInsert context variable, we checked only whether the record is being created; then, only this trigger should execute.
Then again, in the if condition, we checked whether the description field was blank on the new record and added the default description 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.

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

6. Trigger.isUpdate Context Variable in Apex Trigger
In Salesforce Apex, the Trigger.The isUpdate context variable checks whether the trigger is executed as a result of an update operation (e.g., when a user edits a record).
We can use Trigger.isUpdate in trigger code to differentiate between trigger events, such as insert, update, and delete, so we can write logic specific to each case.
Example:
If you want to check whether the existing account name has been changed, update the custom checkbox field Name_Changed__c; it automatically sets it to true.
Before creating the trigger, you can see the account name value in the image below. Also, the name changed checkbox field is not checked (not true).

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 whether the record is being updated; then, only this trigger should execute.
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.

7. Trigger.isDelete Context Variable in Apex Trigger
The Trigger.isDelete context variable indicates whether the trigger is executed as a result of a delete operation, either a single or a 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 that prevents the account from being deleted whenever a user tries to delete it.

Here, we need to use the before delete trigger event to prevent deleting an Account if it has related opportunities.
Using the Trigger.isDelete context variable, we checked only whether the record is being updated; then, only this trigger should execute. 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 from being deleted.
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.

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

8. Trigger.isBefore Context Variable in Apex Trigger
The isBefore context variable in an Apex Trigger is used to determine whether a trigger executes 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 before-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 the logic for the isInsert operation, 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.

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

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

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

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 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 that will contain 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.

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

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:
- Apex Triggers in Salesforce
- How to Compare Two DateTime Values in Salesforce Apex
- Apex Trigger Handler and Helper Class in Salesforce
- Before vs After Triggers in Salesforce: When to Use & Why
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.