function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JeriMorrisJeriMorris 

How a trigger determines whether a field has changed

If I have an "after insert" trigger, I can use something like the following to determine whether a particular field has changed:

if (Trigger.old[0].myfield__c != Trigger.new[0].myfield__c) {
    // field changed
}
else {
    // field didn't change
}
 
Right?

If Trigger.old and Trigger.new have more than one record (because the trigger fired due to several records being changed at once), can I be certain that the records in Trigger.old and Trigger.new are always in the same order? In other words, can I assume that Trigger.old[x] and Trigger.new[x] refer to the same record?

Thanks,

Jeri
Best Answer chosen by Admin (Salesforce Developers) 
XactiumBenXactiumBen
What I always do is loop over all Trigger.new records, then compare that record with the record in the oldMap.

Code:
for (Obj__c o : Trigger.new)
{
if (Trigger.oldMap.get(o.Id).field__c != o.field__c)
{
// do stuff
}
}

 


All Answers

pchadha20pchadha20
Use Trigger.OldMap.<fieldName> and Trigger.NewMap.<fieldName> for their sequential comparison
 
JeriMorrisJeriMorris
Thanks for your reply!

> Use Trigger.OldMap.<fieldName> and Trigger.NewMap.<fieldName> for their sequential comparison

To iterate over items in the maps, I need to index this somewhere -- could you please explain where?

Also, if I understand you correctly, this implies that I can expect Trigger.NewMap and Trigger.OldMap to be in order, but not necessarily Trigger.New and Trigger.Old. Why would that be the case?

Thanks again,

Jeri
MikeGoelzerMikeGoelzer
I think this is the example you want:

http://www.salesforce.com/us/developer/docs/apexcode/index_CSH.htm#apex_triggers_bulk_idioms.htm

Trigger.new and Trigger.old are just arrays so they do preserve order relative to each other.
XactiumBenXactiumBen
What I always do is loop over all Trigger.new records, then compare that record with the record in the oldMap.

Code:
for (Obj__c o : Trigger.new)
{
if (Trigger.oldMap.get(o.Id).field__c != o.field__c)
{
// do stuff
}
}

 


This was selected as the best answer
JeriMorrisJeriMorris
Just what I was looking to find out! Thanks guys!

Jeri