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
Josh VJosh V 

Trigger on Lead before insert NO ID

Hi all,

 

I have a simple trigger which pulls data from the lead object and places it into a custom "Finance" object when the lead is created or updated.  For some reason, the Trigger.new[0].Id is returning NULL in the trigger which fires before insert.  

 

I'm going crazy because I can't see any reason why the Id would be NULL...  Here's my code:

 

 

 

trigger FinanceNew on Lead (before insert) {
	
	Map<String,User> userList = new Map<String,User>{};
	
	// Places each returned user into a map with their sfID as the key
	for(User tmp : [SELECT Id,Name,Email,Phone FROM User]){
	  userList.put(tmp.Id,tmp);
	}
	
	for(integer i = 0; i<Trigger.new.size(); i++){
	
		string leadName = null;
		
		if(Trigger.new[i].FirstName != ''){
			leadName = Trigger.new[i].FirstName + ' ' + Trigger.new[i].LastName;
		}else{
			leadName = Trigger.new[i].LastName;
		}
		
		User ownerInfo = userList.get(Trigger.new[i].OwnerId);
		
		ID leadId = Trigger.new[i].Id; // THIS IS RETURNING NULL!!
		
		Finance__c financeRecord = new Finance__c(
		
			Name = leadName,
			Lead__c = leadId,
			Lead_Email__c = Trigger.new[i].Email,
			Lead_Phone__c = Trigger.new[i].Phone,
			Lead_Owner_Name__c  = ownerInfo.Name,
			Lead_Owner_Email__c = ownerInfo.Email,
			Lead_Owner_Phone__c = ownerInfo.Phone
			
		);
	
		insert financeRecord;
	
	}

}

 

The Lead.Id assignment should be very straight forward.  Every other field pulling directly from the Trigger.new record inserts the correct information.

 

Thanks in advance for any help!

 

Josh

Best Answer chosen by Admin (Salesforce Developers) 
Josh VJosh V

Welp, I figured it out.  The Id is not assigned until after the insert. Before insert there is no Id to hand out.  The correct code should be:

 

trigger FinanceNew on Lead (after insert)

 

All Answers

Josh VJosh V

Welp, I figured it out.  The Id is not assigned until after the insert. Before insert there is no Id to hand out.  The correct code should be:

 

trigger FinanceNew on Lead (after insert)

 

This was selected as the best answer
Aar3538Aar3538

Hello,

 

Since you are on a before insert trigger, the data itself hasn't been inserted into the system.

 

As a result, the Id of the value doesn't exist because the Leads in Trigger.New haven't been placed into salesforce yet.

 

Hope this helps!

 

Edit: too slow ;) Glad you figured it out.

Josh VJosh V

The reply is still appreciated! Thanks for the help. :)