Friday, December 10, 2010

Field Update in Before Trigger Propagates to After Trigger

I confirmed a simple fact in version 20.0 Apex triggers today, that will guide me when writing future trigger code.

If a lookup field is not specified in the DML operation and will not be populated via any other non-trigger means, then a System.debug(Trigger.new); will show that the trigger does not have access to the lookup field value.

However, if the lookup field is populated or updated in the before trigger, then the after trigger will be able to access the new value!

For example, I have a Campaign Feed object that has a Lookup(Campaign) field with an API name of Campaign__c. In my before insert trigger on Campaign_Feed__c, I set Campaign__c to the Id of a newly created Campaign. As a result I am able to then use Campaign__c in my after insert trigger, even though I didn't initially specify a Campaign__c value when inserting the Campaign Feed record.