I am trying to create an Apex Trigger on Lead. After the lead has been inserted,if it has a 'Company' field attached to it, it should match the Company field with an existing Account Name. If a Account Name has been found then the Lead.Account__c field should be set to the found Account.id.
The problem: When performing a bulk insert on lead with a pre-populated Company fields, the Account__c field is not being updated properly( after the insert event has finished, the Account__c field should be set to the Account.id where Account.Name == Lead.Company ).
Example I am trying to insert 100 leads: 99 of those having the Company field set to 'Account1' and 1 having the Company field set to 'Account2'. ( Account1, Account2 already exist in our salesforce instance). The Expected Results should be 99 of the leads have their Account__c field set to the Account1.id and 1 Lead has the Account__c field set to Account2.id. The actual Results 1 lead has the Account__c field set to Account1.id and 1 Lead has the Account__c field set to Account2.id.
Here is the method from the Lead Handler Class which is not working properly:
public void LinkLeadToAccount() {
Map<String,List<id> > Accounts = new Map< String,List<id> >();
Map <id,List<id>> accMap = new Map< id,List<id>>();
List<Lead> leads = new List<Lead>();
List<Lead> leads_to_update = new List<Lead>();
List<id> leadIds= new List<id>();
for (Lead l: newLeads.values()){
if(l.Company!=null)
{
if (!Accounts.containsKey(l.Company)) {
Accounts.put(l.company,new List <Id> {l.id });
}
else{
Accounts.get(l.Company).add(l.id);
}
leads.add(l);
}
}
Set<String> setName = new Set<String>();
List<Account> accts = [select Name,id from Account where Name in :Accounts.keySet()];
for(Account a: accts){
if(!setName.contains(a.name))
{ setName.add(a.name);
accMap.put(a.id,accounts.get(a.Name) );
}
}
for( ID actID : accMap.keySet() ) {
Lead newLead = new Lead();
System.debug('List<account> ' + actID);
for( ID leadID : accMap.get( actId ) ) {
newLead.id = leadID;
newLead.Account__c = actId;
leads_to_update.add(newLead);
break;
}
}
update leads_to_update;
}