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
PlainviewPlainview 

Assign Leads to default user in case of duplicate Accounts.

Hello,

I found this great code that is working (!!) for us now in our Production instance - it assigns new Leads to the Owners of matched Existing Accounts.

To level it up a bit, we would like the code to also route leads to a default user (who will function as the tiebreaker) when the lead is matched to two Account Records for the same company name that have different owners. Can anyone provide a quick line of logic that might do this?

Here's the code:

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);

  }
   
}

}
Best Answer chosen by Plainview
Andy BoettcherAndy Boettcher
I would add some if/then logic to your leadAccountIds loop - use the same containsKey logic you have in the bottom loop to detect if a value is already in the Map for that Account - if so, then do another put (just copy the lines you have) and substitute in the "default user".

All Answers

Andy BoettcherAndy Boettcher
I would add some if/then logic to your leadAccountIds loop - use the same containsKey logic you have in the bottom loop to detect if a value is already in the Map for that Account - if so, then do another put (just copy the lines you have) and substitute in the "default user".
This was selected as the best answer
PlainviewPlainview
Thanks, Andy. I'm new to Apex (just took Dev 401 training and scheduled for Adm 531 in August). Your concept makes sense to me but I'm a little stuck on how to write this out. Any chance you could provide the logic?

Climbing the learning curve,
J