+ Start a Discussion
NakataNakata 

Trigger.new and Error

Good day, I'm new to trigger and would like to get some advice from the guru here. [code] trigger myTrigger on Opportunity (before insert, before update){ for(Opportunity o : trigger.new){ doAction } } [/code] Question : 1. trigger.new is referring to sObject that we calling, means from above sample, it is referring opportunity ? 2. trigger.new and trigger.old basically are same , then when should we use trigger.old ? 3.if there are error show in the debug log and pointing to line of "for loop" above, is that means opportunity is not passing in? what would be the possibility that caused and show below error ? Error : System.NullPointerException: Attempt to de-reference a null object
Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

If you update an opportunity and change the close date from 2/9/2010 to 22/9/2010, the opportunity in trigger.old will have the original close date of 2/9/2010 and the same opportunity in trigger.new will have the new close date of 22/9/2010.  Thus you can check what has changed as part of the update and take any action that is appropriate.

All Answers

bob_buzzardbob_buzzard

Trigger.new is indeed a list of opportunities.

 

Trigger.old is the previous version of the sobject(s) involved in the trigger.  This will not exist for a before insert trigger, as there is no old version.  As to which you should use, it all depends on what you are doing.  I find I'm using trigger.new as I want the latest information.  I use trigger.old to determine if a value has changed as part of the update.

 

I'd be surprised if a before insert/update trigger was invoked with a null trigger.new.  Is it definitely the loop that is the error and not code inside the loop?

 

 

CodeBeeCodeBee

Hi Bob,

 

What do you means by previous sObject ? can you give some example ?

bob_buzzardbob_buzzard

If you update an opportunity and change the close date from 2/9/2010 to 22/9/2010, the opportunity in trigger.old will have the original close date of 2/9/2010 and the same opportunity in trigger.new will have the new close date of 22/9/2010.  Thus you can check what has changed as part of the update and take any action that is appropriate.

This was selected as the best answer