Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lead Trigger before insert not returning lead.Id

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[i].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;

    }

}

Thank you in advance for any help given!

Josh

like image 637
VictorKilo Avatar asked Aug 25 '26 16:08

VictorKilo


1 Answers

For some reason, the Trigger.new[i].Id is returning NULL in the trigger which fires before insert.

SFDC records don't have ID's before they are inserted. The process of insertion creates the ID. You probably want to use after insert.

like image 200
jkraybill Avatar answered Aug 31 '26 08:08

jkraybill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!