Apex Trigger – Null Checking Before Update DML in Apex Trigger

apexbefore-triggernulltrigger

Just a simple question for before update trigger:

// mapFinancialIDtoAccount and mapBillingAccounts being populated here.

for(CustomObject obj : trigger.new)
{
   Account billingAcct = mapFinancialIDtoAccount.get(obj.financialAccountID);

   if (billingAcct != null)
        obj.BillingAccountID = string.valueof(billingAcct.Id);

   if(obj.BillingAccountID != null) 
   {
        Account acct = mapBillingAccounts.get(record.BillingAccountID);
        obj.Name = acct.Name;
   }
}
update trigger.new;

Let's say billingAcct is not null but the update DML is after the for loop, will obj.BillingAccountID have value on if(obj.BillingAccountID != null) even though I've just populated it above? Or do I have to update it twice (one on population of obj.BillingAccountID and the other one to update the whole record in trigger.new)?

Best Answer

Yes you will have the value. You do not need to have update statement for trigger.new in before triggers. The value will automatically update in the records.

You can validate the values using System.debug

obj.BillingAccountID = string.valueof(billingAcct.Id);
System.debug('BillingAccountID ' + obj.BillingAccountID);
Related Topic