I've been working as a developer for about 3 months, so my terminology may be off.
I'm trying to add records to a custom object.
As the new record information is added to a List, the previous additions in the list are changed to the last addition. Inserting the List causes "FATAL_ERROR System.ListException: Before Insert or Upsert list must not have two identically equal elements". All of the list elements are the same as the last addition.
Can someone tell this newbie what he's doing wrong?
trigger BD_Lead_Trigger on Lead (before insert, before update) {
List<NFP_Lead_Account__C> NewLeadAccounts = new List<NFP_Lead_Account__C>();
NFP_Lead_Account__C NewRecord = new NFP_Lead_Account__C();
Map<String, Id> OldLeadAccounts = new Map<String, Id>();
// Put the lead accounts into a map before entering the Trigger loop
for(NFP_Lead_Account__c la : [SELECT BD_Account_Name__c, Id FROM NFP_Lead_Account__c]){
OldLeadAccounts.put(la.BD_Account_Name__c, la.Id);
}
for(Lead newLead : Trigger.new){
// Is this a BD Lead?
If(newLead.RecordTypeId == Schema.SObjectType.Lead.getRecordTypeInfosByName().get('BD Lead').getRecordTypeId()){ // Yes
System.Debug('NewLead.Company : ' + NewLead.Company);
System.Debug('OldLeadAccounts.get(NewLead.Company) : ' + OldLeadAccounts.get(NewLead.Company));
// Does this BD Lead's company exist?
If(OldLeadAccounts.get(NewLead.Company) == null){ // No
NewRecord.BD_Account_Name__c = NewLead.Company;
NewLeadAccounts.add(NewRecord);
System.Debug('Watch this grow -- NewLeadAccounts : ' + NewLeadAccounts);
OldLeadAccounts.put(NewLead.Company, 'a1E2F0000000000000');
}
}
}
// Insert the new Lead Accounts / Companies / Organizations
System.Debug('NewLeadAccounts : ' + NewLeadAccounts);
insert NewLeadAccounts;
// Clear the Lead account map, and put in the new lead accounts before entering the Trigger loop
OldLeadAccounts.clear();
for(NFP_Lead_Account__c la : [SELECT BD_Account_Name__c, Id FROM NFP_Lead_Account__c]){
OldLeadAccounts.put(la.BD_Account_Name__c, la.Id);
}
// Add the new lead account ids to the new BD Leads
for(Lead NewLead : Trigger.new){
NewLead.BD_Lead_Account__c = OldLeadAccounts.get(NewLead.Company);
}
}
Here is USER_DEBUG from the Execution Log: Check out "Watch this grow --".