Thursday, August 1, 2013

Example for Difference between Trigger.new and Trigger.newMap in apex

trigger BeforeInsertTrigger on Account (before insert)
{ set<id> sid = new set<id>(); for(Account A :trigger.new) { 1.sid.add(A.Id);//No error but A.Id contains Null value. 2.system.debug('sid :'+sid);//output Null  
//This line of code i.e,( line number 3) would raise Null Pointer 
Exception becasue trigger.newMap dont work for before trigger 
while Sid will Contain all Ids of records. //If you are using after insert this trigger.newMap would return you the Objects Values in Acc.
3.Account Acc = trigger.newMap.get(A.Id); 4.system.debug('Acc :'+Acc); } }
Note : If you are setting event after insert then this will not raise error it will let you have all data with all Ids in Acc.
Account Acc = trigger.newMap.get(A.Id);
Now you have All record field value in Acc object.


KeyPoints

Trigger.new
 Returns a list of the new versions of the sObject records. Note that this sObject list is only available in   insert and update triggers, and the records can only be modified in before 
triggers.
Trigger.NewMap
A map of IDs to the new versions of the sObject records.Note that this map is only
available in before update, after insert, and after update triggers.
Note :   Trigger.newMap dont work for before insert while Trigger.New works fine for holding all Ids of records while inserting.According to the docs, Trigger.new returns a list, which are ordered, and Trigger.newMap returns a map - which are unordered. The docs specifically state you should not rely on the ordering of a map's elements.What to use depends on what you're doing - if you have an ID of an object you need to do something with, using the map makes more sense as you can use newMap.get(). Otherwise you'd have to loop over all the elements in Trigger.new and look for a matching ID. Similarly, if you have multiple loops over each item the trigger is operating on, the list returned by Trigger.new may be the better bet