Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 8 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.