O Reference, why art thou null !? Apex Bloopers Series : 1
I have recently acquired a penchant for responding to posts on the Salesforce Discussion Boards. Its the only way I know of constantly challenging the limits of my limited knowledge about this rapidly evolving platform.
As part of the Apex Bloopers series, I aim to capture some of the most common mistakes we make inadvertently, and wonder why the Universe is conspiring against us when everything looks like it should ! Some of these are not really mistakes, but some things are just not so obvious when you get started with Apex. So Bloopers, for want of a more catchy title !
The first one that springs to mind is a case where you check for relationship references in a before / after insert trigger.
Now if you try inserting a Contact and look at the debug logs, you will see that con.Account.Name evaluates to null. However the AccountId field does hold the Id of the related Account. That does seem a bit odd when you come across it for the first time. It isn’t exactly intuitive.
The reason this happens is because in before / after insert triggers, relationship fields are not reference-able directly, as there is no way for Salesforce to know which fields of the related object it should load and make available. It cannot load all Account fields and make them available, for reasons of efficiency (err… or so I’m told !)
So, if you need to access fields on related objects, you will first have to query for them and then use the references.
Needless to say (really !?), in a before / after Update trigger, the Contact.Account reference will evaluate to a value !
So much for this time, until we meet again, May the Force.com be with You !