Salesforce Context Variables
Last updated on Nov 21, 2023
- What are Salesforce trigger context variables and why do we need them?
- Descriptions of Trigger Context Variables
- Considerations for Trigger Context Variables
- Conclusion
What are Salesforce trigger context variables and why do we need them?
Trigger context variables offer details about the Trigger that is currently running. We need a mechanism to find information about the Trigger that is being executed while writing Trigger logic. Trigger context variables come into play here. We may get information about the Trigger as well as the records for which the Trigger is being executed by utilizing the Trigger class in Apex. Trigger context variables essentially give us information about the Trigger that is currently running.
Let's have a look at some real-world instances of Context variables in Triggers.
Wish to make a career in the world of salesforce? Start with HKR'S salesforce online training !
Business requirement
The company has asked you, the developer, to implement some code that will count the number of times a contact record in Salesforce has been updated.
Technical Solution
On the Contact object, you'll add a custom field called Count_of_Updates__c. There will be no decimal places in the number field. Then, on the Contact object, you'll construct a trigger to ensure that this count field is always up to date.
The code
Some context variables will be used in this example. We're going to write this as a Before Update trigger to make this code as efficient as possible. We won't need to use another DML statement to update the contact as a result of this. Remember that we'll be keeping the code bulky to adhere to best practices.
The context variables we'll need for this code are listed below.
- Trigger.new - This context variable will allow us to access the Contact records that are now being updated.
- Trigger.isUpdate - We'll be able to check if a record is being modified using this context variable.
- Trigger.isBefore - We can use this context variable to ensure that the Trigger is in the before mode.
When using Trigger Context Variables, there are a few things to keep in mind.
- Trigger.new cannot be changed in After DML operations since it has already been stored; however, you can change it in a Before DML operation, as we did in the previous example.
- If you try to change trigger.new in an after DML operation, you'll get an error like this: execution of AfterUpdate caused by: System.FinalException: Record is read-only ()
If the trigger has an After parameter, and no check is in place to update our contact records only in the before update context, an error will be thrown.
Get ahead in your career by learning Salesforce through hkrtrainings Salesforce Training in Hyderbad !
Salesforce Training
- Master Your Craft
- Lifetime LMS & Faculty Access
- 24/7 online expert support
- Real-world & Project Based Learning
Descriptions of Trigger Context Variables
Let's have a look at the rest of the Trigger context variables and see what they can do.
- size: Returns a count of the number of records being processed by the trigger
- operation type: The current Trigger context is returned as an enum. We can use these enums to see what context the Trigger is in.
Here's an example switch statement that checks all of the enum's values and can be used to fire trigger logic in contexts that are targeted.
switch on Trigger.operationType {
when BEFORE_INSERT {{
} //Before Insert logic
} when BEFORE_UPDATE {
//Before update logic
} when BEFORE_DELETE {
//Before delete
} when AFTER_INSERT {
//After Insert logic
} when AFTER_UPDATE {
//After Update logic
} when AFTER_DELETE {
//After Delete logic
} when AFTER_UNDELETE {
//After UnDelete logic
}
}
- oldMap: Prior to the update operation, it returns a Map from the record Id to the related record, e.g. Map
. Only update and remove triggers have this option. There are no old values in insert triggers.
This map is highly handy if you need to find an older version of a record you're looking at, such as a previous version of a record you're looking at. Account account = Trigger.new[0]; Account oldAccount = Trigger.oldMap.get(account.Id); - old: Prior to the update process, this method returns a list of the records. Only update and delete triggers have this feature. There are no old values in insert triggers. If you want to see if any field values have changed, such as Case.Status, you can use Trigger.old.
- newMap: Returns a map from a record Id to the record it belongs to. For instance, Map
. This map will only be viewable once the record Ids have been filled in. As a result, the Map in the Before Insert Trigger cannot be accessed. After insert, before the update, and after undelete triggers all support the newMap Context variable. - new: The list of records being processed by the Trigger is returned. Only insert, update, and undelete operations are supported by Trigger.new.
- isUndelete: When a record is recovered from the recycle bin, this method returns true.
Subscribe to our YouTube channel to get new updates..!
- isAfter: If the records being inserted/updated have been committed to the database, this method will return true. At this time, the record IDs and formula fields will be available.
- isBefore: If a Trigger is in Before context, it means that the record inserted/updated has not yet been committed to the database. At this moment, the Records can still be changed (without additional DML)
- isDelete: When a record was just deleted, such as when a User deleted an Account record in Salesforce, this method returns true.
- isUpdate: When a record in Salesforce is being updated, such as when a user has just hit Save on an already existing Account in Salesforce, this method returns true.
- isInsert: When a record is being inserted into Salesforce, such as when a User has just saved a new Account, this method returns true.
- isExecuting: If a Trigger is currently being run, this method returns true. If code could be called from several places, such as a rest API or a lightning component controller, this is useful.
Click here to get frequently asked Salesforce interview questions & answers
Considerations for Trigger Context Variables
The following list explains the trigger context variables considerations.
- In Apex DML operations, trigger.new and trigger.old isn’t allowed.
- Only before triggers can you use trigger.new to update an object's own field values.Trigger.new is not preserved in all after triggers, resulting in a runtime exception.
- It's always read-only in trigger.old.
- The trigger.new cannot be deleted.
Conclusion:
Thus we have learned the salesforce context variables and understood the real-world trigger instances’ requirements, solution, and code. We have also gone through looking into various descriptions of trigger context variables such as oldMap, newMap, isAfter, isUpdate, isBefore, etc., and other considerations.
Related Articles:
About Author
A technical lead content writer in HKR Trainings with an expertise in delivering content on the market demanding technologies like Networking, Storage & Virtualization,Cyber Security & SIEM Tools, Server Administration, Operating System & Administration, IAM Tools, Cloud Computing, etc. She does a great job in creating wonderful content for the users and always keeps updated with the latest trends in the market. To know more information connect her on Linkedin, Twitter, and Facebook.
Upcoming Salesforce Training Online classes
Batch starts on 21st Nov 2024 |
|
||
Batch starts on 25th Nov 2024 |
|
||
Batch starts on 29th Nov 2024 |
|