Thursday, June 30, 2011

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){
        sid.add(A.Id);
        system.debug('sid :'+sid);
        //This line of code 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.
        Account Acc = trigger.newMap.get(A.Id);
        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(Acc.Id);
Now you have All record field value in Acc object.

No comments:

Post a Comment