These context variables provide information about the timing of the trigger execution. These variables are contained in the System.Trigger class and are commonly used to control the flow of logic within triggers.
•\ Trigger.isBefore: Returns true if the trigger was fired before any record was saved. This variable is often used to perform actions or validations before the records are saved.
•\ Trigger.isAfter: Returns true if the trigger was fired after all records were saved. This variable is often used to perform actions or calculations after the records have been saved.
The following example is designed to execute after a Contact record is updated. It monitors changes in the Email field of Contact records and creates Chatter feed items for Contacts where the email has been updated.
trigger ContactEmailUpdate on Contact (after update) {
for (Contact contact : Trigger.new) {
// Check if the email field has been changed
if (contact.Email != Trigger.oldMap.get(contact.Id).Email) {
}
}
for (Contact contact : updatedContacts) {
FeedItem feedItem = new FeedItem();
feedItem.ParentId = contact.Id;
feedItem.Body = ‘The email for the contact ‘ + contact.Name
feedItems.add(feedItem);
}
}
}
}
In this example:
•\ It checks if it is running after the update operation if Trigger.isAfter.
•\ It creates a list updatedContacts to hold the Contacts that have been
updated.
•\ It iterates through the Contacts in Trigger.new the updated Contacts
and compares the new Email value with the old Email value from Trigger.oldMap.
•\ If the Email has changed, the Contact is added to the
updatedContacts list.
•\ For each updated Contact, a Chatter feed item is created.
IsExecuting
Common use cases for this variable include
•\ Avoiding Recursive Triggers: You might use isExecuting to prevent a trigger from firing recursively.
•\ Handling Trigger Logic in Utility Classes: Utility classes that are called from triggers might use isExecuting to adjust their behavior based on whether they are invoked within a trigger.
•\ Logging and Debugging: Logging or debugging statements might be conditionally included based on whether the code is running in a trigger context.
Having multiple triggers on the same object can lead to unpredictable execution order. Like recursion often occurs when a trigger performs an action that causes another trigger to fire. The problem of recursive triggers in Apex occurs when a trigger on a Salesforce object performs an action that causes the trigger to be invoked again, resulting in an infinite loop. This can lead to performance issues, governor limit errors, and unexpected behavior in your application.