10 - Trigger Part 2 : Trigger context variables

 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 VariableDescriptionUse Case
Trigger.newContains 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.oldContains 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.newMapProvides 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.oldMapProvides 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.isInsertReturns true if the trigger event is insert.Use for code that should only run during inserts.
Trigger.isUpdateReturns true if the trigger event is update.Use for code that should only run during updates.
Trigger.isDeleteReturns true if the trigger event is delete.Use for code that should only run during deletions.
Trigger.isBeforeReturns true if the trigger is executing before the record is saved.Use for before triggers (e.g., validation or data setup).
Trigger.isAfterReturns true if the trigger is executing after the record is saved.Use for after triggers (e.g., logging, notifications).
Trigger.isUndeleteReturns 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.sizeReturns 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:

apex
trigger 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.new to access new record data.
  • Using Trigger.oldMap to 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 true if 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.new or Trigger.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_INSERT
    • TriggerOperation.AFTER_UPDATE
    • TriggerOperation.AFTER_DELETE
    • TriggerOperation.AFTER_UNDELETE
    • TriggerOperation.BEFORE_INSERT
    • TriggerOperation.BEFORE_UPDATE
    • TriggerOperation.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');

                }

            }

        }

    }

}


Comments

Popular posts from this blog

API Names in Salesforce

18 - LWC - BEST PRACTICES - For accessing HTML elements and their values in JavaScript

6 - Object Relationships (Lookup and Master-Detail and Junction Objects)