function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
werewolfwerewolf 

Trigger.newMap is null in before insert?

Hi all,

I was happily humming along writing my Case before insert trigger, but when I wrote my tests, they all failed.  This appears to be due to the fact that Trigger.newMap is coming up null, and I'm trying to use it late in my trigger.  Meanwhile, Trigger.new works just fine.

I added this code to the very beginning of my trigger:

trigger CaseAutocreateContact on Case (before insert) {
      System.debug(Trigger.newMap == null?'Trigger.newMap is null!':'Trigger.newMap is populated.');

And lo and behold when I run my tests I see:

    20081107011750.678:Trigger.CaseAutocreateContact: line 2, column 5: Trigger.newMap is null!

What gives here?  How can Trigger.new be populated but Trigger.newMap be null?  My trigger is using the 14.0 endpoint.

Thanks.
werewolfwerewolf
Ah, sorry.  This one's a head-slapper.  Of course there's no newMap in before insert -- the Ids haven't been assigned yet.
amitashtekaramitashtekar

Note that newMap is only available in before update, after insert, and after update triggers.

 

for more clarification

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_context_variables.htm

alaschgarialaschgari

Workaround to have something equal to trigger.newMap available:

 

trigger trgr_Opportunity on Opportunity (before insert)
{
	map<Id, Opportunity> mapOppsNew;
	
	if(trigger.isBefore)
	{
		if(trigger.isInsert)
		{
			mapOppsNew = new map<Id, Opportunity>();
			
			for(Opportunity o : trigger.new)
				mapOppsNew.put(o.Id, o);
		}
	}	
}

 

Nash.GNash.G

Why should this workaround work? The records shouldn't have any ids assigned in before insert correct? Isn't that why newMap isn't available in before triggers.

Paras JainParas Jain
newMap is only available in , after insert,before update, after update, also in after undelete triggers.