Apex Aide apexaide

Trigger.newMap & Trigger.oldMap Context Variable in Apex Trigger

Salesforce FAQs· ·Intermediate ·Developer ·8 min read
Summary

Trigger.newMap and Trigger.oldMap are essential Apex trigger context variables that provide maps of record IDs to their new and old versions respectively, allowing more efficient and clear access to record states during various trigger events. These maps are especially useful when comparing old and new values, such as enforcing validation rules or updating related records based on changes. Practical examples show how to update contacts’ mailing cities based on account billing city changes or prevent unauthorized modifications to opportunity amounts. Leveraging these maps helps streamline trigger logic and maintain data integrity in Salesforce orgs.

Takeaways
  • Use Trigger.newMap to access the latest record values by record ID in after and before update triggers.
  • Leverage Trigger.oldMap to compare previous record values during update or delete operations.
  • Implement validation logic by comparing Trigger.oldMap and Trigger.newMap values to prevent unauthorized changes.
  • Fetch related records efficiently using Trigger.newMap.keySet() to operate on child records.
  • Understand the availability of Trigger.newMap and Trigger.oldMap in different trigger contexts to avoid runtime errors.

In Salesforce, Apex triggers automate processes and apply custom logic during specific database operations, such as insert, update, delete, and undelete. In that, we use Trigger.newMap and Trigger.oldMap in Salesforce Apex, which are other types of context variables that return maps of the old versions of  sObject  records. When we start learning Apex Triggers in Salesforce, everything looks simple at first. We understand: What is a trigger When it runs How to write basic code But then we see something like this inside the trigger. Here, confusion starts. Trigger.newMap Trigger.oldMap In this article, we will learn about Trigger.newMap & Trigger.oldMap context variable in Apex trigger. In this, I will explain the following points: What is this? Why Map? When should we use it? Why not just use Trigger.new or Trigger.old? What is Trigger.newMap in an Apex Trigger in Salesforce? Trigger.newMap is a Map collection . In A pex Map, data is stored in key-value format.

ApexValidation & Data QualityTrigger.newMap & Trigger.oldMap Context Variable in Apex Trigger