Take the Contact object. If I write a trigger on the Contact object, I'll have access to the
AccountId
value for each Contact handled by the trigger, but I will not have access to the related values such as Account.Name
or Account.Owner.Name
. Usually, to get around this, I would need to write SOQL within the trigger to retrieve the related values for use within the trigger.This has personally been a great pain in my side, and it only seems to grow more intense as time goes by. Now, I'm stuck at trying to figure out how to get at those related values in another class that's used by the trigger. After some frustration, I came up with an idea.
What if I used a static variable stored in a utility class that I could set and get at will, wherever as long as I'm within the same trigger context? Well, that'd be pretty cool. To that end, I arrived at the concept for a
TriggerContext
class.I won't spend too much time discussing it, as a demo's worth a million words. The classes and triggers inside TriggerContextDemo-1.0.zip can be added to any sandbox or developer org. To see the effects, simply create a new contact record, save it, and then update it by associating an account.
As I'm wrapping up this post, I realize that another, more straightforward approach to handling this could be to have the trigger's associated utility class automatically assign the related records back to the trigger records by writing to the sObject fields and not to the record ID fields. I'll look into this more tomorrow as I try to handle related values in a real project.