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
Tristan JonesTristan Jones 

Assigning a lead to an account owner when the company is an approximate match.

Hi all, 

I have apex trigger (pasted below) to assign a lead to a user if the company given is the same as an account. The problem I'm having is that lots of leads coming through our website, seminars, trade shows etc only have approximate account names which do not get assigned through my trigger.

For example if Joe Bloggs is the account owner for Acme Compnay. LTD and a lead is pushed into Salesforce with the Acme Company. LTD  the lead gets allocated to Joe, however if the company on the lead is only Acme, then it doesn't get allocated. 

What I'd like to do is a bit like the range_lookup on the end of Vlookup formulae in Excel, where you can specify if it needs to be an exact or approximate match. Is there anyway to do this in my trigger? 

Many thanks, 

Tristan 


trigger addAccount on Lead (before Insert, before Update){

List<string> companies=new list<string>();

For (lead l:trigger.new){
  companies.add(l.company);
}


List<Account> leadAccountIds=[Select Id, OwnerId, Name FROM Account WHERE Name IN: companies];

Map<String, Id> acctNameId=new Map<String, Id>();
Map<String, Id> acctNameOwner=new Map<String, Id>();
 
For (Account a:leadAccountIds){
  acctNameId.put(a.name,a.Id);
  acctNameOwner.put(a.name,a.ownerId);
}


For (Lead l2:trigger.new){
  if(acctNameId.containsKey(l2.company)){
    l2.Account__c=acctNameId.get(l2.company);
    l2.ownerId=acctNameOwner.get(l2.company);
  }
}
}
 
Lokeswara ReddyLokeswara Reddy
Hi Tristan, 

You can optimize the code as suggested here,

String[] leadArray = new String[<SIZE_OF_TRIGGER>]; // Number of records in trigger.new

List<Lead> leadList = trigger.new;
Integer i = 0;
for(Lead leadObj:leadList){
    leadArray.set(i,leadObj.Name+'%'); // make sure lead name should be in '', example 'name1%', debug this and add '' if required here
    i = i+1;
}

List<Account> leadAccountIds=[Select Id, OwnerId, Name FROM Account WHERE Name Like: leadArray];

// Your logic to compare lead and account names
// User containsIgnoreCase() and startsWithIgnoreCase() methods
// refre for String methods - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm
 
Let me know if this works good for you.