Trigger Context Variable in Salesforce Apex

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:

  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