In Apex Triggers, there are several context variables that are available to help manage the state of the trigger and access information about the records being processed. Here are some of the key context variables:
Trigger:
The Trigger object represents the current trigger and provides information about the trigger’s context. You can use the Trigger object to access the name of the trigger, the trigger’s Id, and the trigger’s context.
Syntax:
Trigger currentTrigger = Trigger.isExecuting;
Example:
System.debug(‘Trigger Name: ‘ + Trigger.getName());
Trigger.new:
The Trigger.new context variable is a list of sObjects that represent the new versions of the records being inserted, updated, or deleted. You can use the Trigger.new context variable to access the new values of the records and to modify the records before they are saved to the database.
Syntax:
List<sObject> newRecords = Trigger.new;
Example:
for (Account a : Trigger.new) {
a.Name = ‘Modified: ‘ + a.Name;
}
Trigger.old: The Trigger.old context variable is a list of sObjects that represent the old versions of the records being updated or deleted. You can use the Trigger.old context variable to access the old values of the records and to compare the old values with the new values to determine what has changed.
Syntax:
List<sObject> oldRecords = Trigger.old;
Example:
for (Account a : Trigger.old) {
System.debug(‘Old Name: ‘ + a.Name);
}
Trigger.isBefore:
The Trigger.isBefore context variable is a Boolean value that indicates whether the trigger is executing before or after the record is saved to the database.
Syntax:
Boolean isBefore = Trigger.isBefore;
Example:
if (Trigger.isBefore) {
System.debug(‘Trigger is before the record is saved.’);
}
Trigger.isInsert:
The Trigger.isInsert context variable is a Boolean value that indicates whether the trigger is executing for an insert operation.
Syntax:
Boolean isInsert = Trigger.isInsert;
Example:
if (Trigger.isInsert) {
System.debug(‘Trigger is executing for an insert operation.’);
}
Trigger.isUpdate:
The Trigger.isUpdate context variable is a Boolean value that indicates whether the trigger is executing for an update operation.
Syntax:
Boolean isUpdate = Trigger.isUpdate;
Example:
if (Trigger.isUpdate) {
System.debug(‘Trigger is executing for an update operation.’);
}
Trigger.isDelete:
The Trigger.isDelete context variable is a Boolean value that indicates whether the trigger is executing for a delete operation.
Syntax:
Boolean isDelete = Trigger.isDelete;
Example:
if (Trigger.isDelete) {
System.debug(‘Trigger is executing for a delete operation.’);
}
Trigger.size:
The Trigger.size context variable is an integer value that represents the number of records being processed by the trigger.
Syntax:
Integer numRecords = Trigger.size;