10 - Trigger Part 2 : Trigger context variables
- Get link
- X
- Other Apps
In Salesforce, trigger context variables are special variables provided within Apex triggers that give access to the records and other information relevant to the operation that caused the trigger to fire. These context variables help developers handle different scenarios and ensure that triggers behave correctly based on the operation and its state.Here's a summary of the key trigger context variables:
| Context Variable | Description | Use Case |
| Trigger.new | Contains the list of new records that are entering the system (available for insert and update events). | Modify fields on new records before they’re saved. |
| Trigger.old | Contains the list of the original versions of records (only available for update and delete events). | Compare old and new field values in an update operation. |
| Trigger.newMap | Provides a map of IDs to the new versions of records (available for insert and update events). | Access specific records by ID for easy reference. |
| Trigger.oldMap | Provides a map of IDs to the old versions of records (only available for update and delete events). | Access previous values of specific records by ID. |
| Trigger.isInsert | Returns true if the trigger event is insert. | Use for code that should only run during inserts. |
| Trigger.isUpdate | Returns true if the trigger event is update. | Use for code that should only run during updates. |
| Trigger.isDelete | Returns true if the trigger event is delete. | Use for code that should only run during deletions. |
| Trigger.isBefore | Returns true if the trigger is executing before the record is saved. | Use for before triggers (e.g., validation or data setup). |
| Trigger.isAfter | Returns true if the trigger is executing after the record is saved. | Use for after triggers (e.g., logging, notifications). |
| Trigger.isUndelete | Returns true if the trigger event is undelete (record is restored from the Recycle Bin). | Use for code that should run only when a record is undeleted. |
| Trigger.size | Returns the total number of records in the Trigger.new or Trigger.old list. | Check the number of records affected in bulk operations. |
Example of Using Context Variables
Here's a sample trigger that uses several context variables to check if an Opportunity is updated and then logs changes to a custom field:
apextrigger OpportunityUpdateTrigger on Opportunity (before update) { for (Opportunity opp : Trigger.new) { Opportunity oldOpp = Trigger.oldMap.get(opp.Id); // Check if the custom field has changed if (opp.CustomField__c != oldOpp.CustomField__c) { System.debug('Custom field changed from ' + oldOpp.CustomField__c + ' to ' + opp.CustomField__c); } } }
This example demonstrates:
- Using
Trigger.newto access new record data. - Using
Trigger.oldMapto access the original (old) values of records. - Logging changes only when specific fields have been modified.
These context variables allow developers to handle complex scenarios in a streamlined and controlled way.
----
In Salesforce triggers, the context variables Trigger.isExecuting, Trigger.size, and Trigger.operationType provide additional control and information about the trigger execution context.
1. Trigger.isExecuting
- Description: Returns
trueif the current code is being executed within a trigger. - Purpose: Useful to check if the code is running within the trigger context, especially when the same code could be used in other places (like within an Apex class or helper method).
- Example:apex
if (Trigger.isExecuting) { System.debug('This code is running within a trigger'); }
2. Trigger.size
- Description: Returns the total number of records that are part of the current trigger context (records in
Trigger.neworTrigger.old). - Purpose: Primarily used for bulk processing to know how many records are being processed in a single batch.
- Example:apex
System.debug('Total records in trigger: ' + Trigger.size);
3. Trigger.operationType
- Description: Returns an enum (TriggerOperation) that represents the specific type of operation causing the trigger to fire.
- Possible Values:
TriggerOperation.AFTER_INSERTTriggerOperation.AFTER_UPDATETriggerOperation.AFTER_DELETETriggerOperation.AFTER_UNDELETETriggerOperation.BEFORE_INSERTTriggerOperation.BEFORE_UPDATETriggerOperation.BEFORE_DELETE
- Purpose: Allows more precise checks on the type of operation, especially useful when handling logic that might need to distinguish multiple operations in the same trigger.
- Example:apex
if (Trigger.operationType == TriggerOperation.BEFORE_INSERT) { System.debug('This is a before insert trigger'); }
-----------------------------------EXAMPLE CODE -----------------------------------------
trigger LeadTrigger on Lead (before insert, before update, after update) {
switch on Trigger.operationType {
when BEFORE_INSERT {
for (Lead newLead : Trigger.new) {
// Set default Lead Source if blank
if (String.isBlank(newLead.LeadSource)) {
newLead.LeadSource = 'Other';
}
// Validate that Industry field is not blank
if (String.isBlank(newLead.Industry)) {
newLead.Industry.addError('The Industry field cannot be left Empty');
}
}
}
when BEFORE_UPDATE {
for (Lead updatedLead : Trigger.new) {
// Set default Lead Source if blank
if (String.isBlank(updatedLead.LeadSource)) {
updatedLead.LeadSource = 'Other';
}
// Prevent direct status change from "Open - Not Contacted" to "Closed" statuses
Lead oldLead = Trigger.oldMap.get(updatedLead.Id);
if ((updatedLead.Status == 'Closed - Converted' || updatedLead.Status == 'Closed - Not Converted')
&& oldLead.Status == 'Open - Not Contacted') {
updatedLead.Status.addError('You cannot directly close an open lead record');
}
}
}
}
}
- Get link
- X
- Other Apps
Comments
Post a Comment