Activity Forums Salesforce® Discussions Where to use Trigger.new and Where to use Trigger.newMap?

  • Saurabh

    Member
    April 21, 2017 at 2:09 pm

    Hello Suraj

    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.

    suppose you have a custom object Custom_obj__c

    Trigger.New means it is a List<Custom_obj__c>

    and

    Trigger.NewMap means it is a map<Id, Custom_obj__c>
    In before insert context your Trigger.NewMap always be null because in before context records is not submitted to database so Id is not generated that's why in before insert we don't useTrigger.NewMap

    But in After insert Id is generated so We can use Trigger.NewMap

    In case of before and After update since id is already generated in Insert event.

    SO we can use Trigger.NewMap in before and After update

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos