Home > Uncategorized > O Reference, why art thou null !? Apex Bloopers Series : 1

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 !

About these ads
Categories: Uncategorized
  1. Makarand Parab
    April 4, 2011 at 4:54 pm

    Hi Ritesh
    Thanks for the info, being not in touch with SFDC tech due to other commitment, reading ur blog was of great help. It took me back to the time when i was writing the apex code and facing all these issue. Please keep adding to the blog much needed for me and helpful for quick knowledge update.

    Regards
    Makarand Parab

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 316 other followers

%d bloggers like this: