4

I have a simple trigger like:

trigger littleTrigger on Custom__c (before insert) {
    Set<Id> idSet = Trigger.newMap.keySet();
    //Some stuff
}

Why could the second line throw a null pointer exception?

When I code it like:

trigger littleTrigger on Custom__c (before insert) {
    Set<Id> idSet = new Set<Id>();

    for (Custom__c d : Trigger.New)
        idSet.add(d.Id);
}

It works just fine.

1 Answer 1

12

From the Trigger Context Variables documentation:

  • Trigger.new: this sObject list is only available in insert and update triggers
  • Trigger.newMap: this map is only available in before update, after insert, and after update triggers

In a "before insert" trigger, the sObjects don't yet have ID values so a Trigger.newMap keyed by the sObject ID can't be made available and Trigger.newMap returns null. But a list of the sObjects (again without IDs) can be made available.

2
  • Keith comments are true, but why is the second option working at all? you are using trigger.new in a before insert call and retrieving the record Id which it doesn't exist yet
    – Emilio
    Oct 13, 2014 at 6:27
  • @Emilio I think the "works fine" in the question here just means no null pointer exception. The idSet will end up with only one entry, the value null, and so is not useful. For this "before insert" case, the position in the Trigger.new list can sometimes be used to identify the SObjects. Also nothing can be referencing the SObjects as they are not yet inserted so their ID values aren't/can't be needed.
    – Keith C
    Oct 13, 2014 at 7:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .