Comparing new values vs. old values in APEX Trigger

I came across a situation today where I needed to compare new vs. old values in an APEX Trigger to determine a course of action.  Here is a slick little way to do this without having to worry about if Salesforce decided to correctly order your trigger.old in the same way that trigger.new is.

Here is the APEX Trigger:

trigger historyCheckerLogic on Event (before update)

///////////////////////////////////////
// This trigger handles record updates from the EVENT object
// Reference:  (class) historyChecker.checkPreviousValues()
// (other nice little header info)
///////////////////////////////////////

// Declare APEX Class where work will be done (I try not to ever do any work inside of a trigger)
public historyChecker clsHistoryChecker = new historyChecker();

// Put trigger.new and trigger.old data into Lists declared in my APEX Class
clsHistoryChecker.lstNewEvents = Trigger.new;
clsHistoryChecker.lstOldEvents = Trigger.old;

// Trigger Logic – Before Update
if(trigger.isBefore && trigger.isUpdate) {
clsHistoryChecker.checkPreviousValues();
}

}

Here is the APEX Class:

public class historyChecker {

///////////////////////////////////////
// This class handles logic from the historyCheckerLogic trigger
// (other nice little header info)
///////////////////////////////////////

public List<Event> lstNewEvents = new List<Event>();
public List<Event> lstOldEvents = new List<Event>();

public void checkPreviousValues() {

///////////////////////
// This method compares old values to new values from the historyCheckerLogic trigger
///////////////////////

// Declare method variables
Map<Id, Event> mapVerifyOldEvents = new Map<Id, Event>();

// Create initial Map of old Events
for(Event evtOld : lstOldEvents) { mapVerifyOldEvents.put(evtOld.Id, evtOld); }

// Loop through lstNewEvents and check old values
for(Event evtNew : lstNewEvents) {

if(evtNew.ActivityDate != mapVerifyOldEvents.get(evtNew.Id).ActivityDate) {

// The values are NOT the same, do whatever logic you want…
evtNew.addError(‘Ummm, you can’t change this field!’);

}

}

}

}

I remember looking high and low for a way to efficiently do this a while back – so hopefully if you’ve found my page I’ve helped you out a little with your question.  Please feel free to ask me other related questions in the comments below.

Thanks for readying and happy coding!