Showing posts with label update. Show all posts
Showing posts with label update. Show all posts

Friday, November 25, 2011

Using IsPersonAccount Field in Account Triggers

Great news! It looks like the IsPersonAccount field is always available for use in Apex triggers, without the need to retrieve the field values using SOQL!

The following test was used to reach this conclusion (in Winter '12):
  1. Create a trigger that activates or fires before/after insert, before/after update and before/after delete.
  2. Add code to the trigger to check every record in Trigger.new and in Trigger.old with the following assertion: System.assert(accountInTrigger.get('ispersonaccount') != null);
  3. Create a test method to insert, update and then delete an Account.
  4. Verify that the test passes.

Optionally, one can also use the following code in the trigger to take a deeper look at the basic information that's always available, depending on what caused the trigger to fire:
System.debug('Trigger.new = ' + Trigger.new);
System.debug('Trigger.old = ' + Trigger.old);

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.