Workflow is great. I can simply and declaratively make changes, and can easily update things like email templates, criteria, tasks, etc. without using Eclipse and writing/running unit tests.
Sometimes, however, workflow isn’t enough; we need to use a trigger.
Today, I had a use-case that when a DateTime field is filled, a contact (identified via a lookup on a parent object – so a grandparent record) should receive a notification. That’s easy enough to do with a ISCHANGED(DateTimeField__c) workflow criteron, but the Email Alert can’t “find” the contact. A trigger is necessary.
Here’s how I coded the trigger:
trigger InterviewUpdates on Interview__c (after update, before update) {
if(Trigger.IsBefore){
for(Interview__c i : Trigger.New){
if(i.Date_and_Time__c != Trigger.oldMap.get(i.id).Date_and_Time__c){
// Send email to applicant, passing Interview, DateTime, and Contact
// (which we found via a query coded outside the loop to avoid governor limits)
}
}
}
}
I’ve left out a lot of parts here, but I hope that the main bit of using Trigger.oldMap to find the old value and compare it to the new one comes through.
Happy coding!
E.J. Wilburn says
Trigger.New and Trigger.Old are in the same order, you can do this a little faster and easier like this:
trigger InterviewUpdates on Interview__c (after update, before update) {
if(Trigger.IsBefore){
for ( Integer x = 0; x < Trigger.New.size(); x++ )
if ( Trigger.New[x].Date_and_Time__c != Trigger.Old[x].Date_and_Time__c ) {
// Send email to applicant, passing Interview, DateTime, and Contact
// (which we found via a query coded outside the loop to avoid governor limits)
}
}
}
}
David Schach says
Interesting. We differ in that I don’t think initializing a counter and doing a for loop like that is at all easier. In general, keeping variables to a minimum seems a best-practice.
We get the same result, but I think mine doesn’t add confusion with ‘x’ floating around.