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
KalyaniKalyani 

Trigger to update Lead Owner with a Different User

Hi,

 

I have a custom object "Branch __c" and it has fields "Name" which is the name of a branch and "Branch User" which is a look up field for a User. On leads i have a look up to branch object to select the "branch". When a branch is selected on lead i want the lead Owner field to be changed or the lead be assigned to "Branch User" on the branch object. I am using the following trigger to update the field but i am not able to so. Can you please correct the code for me.

 

trigger Lead_UpdateOwner on Lead(before insert,before update)
{
    Map<Id, String> ownerMap = new Map<Id, String>();
    for (Lead lead : Trigger.new)
    {
        ownerMap.put(lead.OwnerId, lead.Branch__c);
    }
    
    List<String> leadBranchNames = new List<String>();
    leadBranchNames = ownerMap.values();    
     
       
   Map<String, String> branchMap = new Map<String, String>();
    
   for (Branch__c b : [select Name, Branch_MC__c from Branch__c where Name in :leadBranchNames])
    
    {
         branchMap.put(b.Name, b.Branch_MC__c);
    
    }
    
    List<String> branchMcs = new List<String>();
    branchMcs = branchMap.values();
      

    if (ownerMap.size() > 0)
    {
        for (User[] users : [SELECT Id, Name FROM User WHERE Id IN :branchMcs])
        {
            for (Integer i=0; i<users.size(); i++)
            {
                ownerMap.put(users[i].Id,null);
            }
        }
       
    }
}

 

Best Answer chosen by Admin (Salesforce Developers) 
KalyaniKalyani

Its Working fine. Thanks a lot.

All Answers

Naidu PothiniNaidu Pothini

for (User[] users : [SELECT Id, Name FROM User WHERE Id IN :branchMcs])

 

 

Did you check whether the query is returning any values?

 

branchMCS will have the values b.Branch_MC__c

 

Try changing the query.

KalyaniKalyani

No nothing is updating for me. So any sugesstions on what the query should be? 

Naidu PothiniNaidu Pothini

trigger Lead_UpdateOwner on Lead(before insert,before update)
{
    Set<String> branchIds = new Set<String>();
    for (Lead lead : Trigger.new)
    {
        branchIds.add(lead.branch__c);
    }
    
    List<Branch__c> branchList = [SELECT Id, Branch_MC__c FROM Branch__c WHERE Id IN :branchIds];
    
    for (Lead l : Trigger.new)
    {
        for (Branch__c b : branchList)
        {
            if(l.branch__c == b.Id)
            {
                l.OwnerId = b.Branch_MC__c;
            }
        }
    
    }
}

 

I assumed that Branch_MC__c is the Branch User.

I am not sure whether this works or not but try this and let me know if it doesnt work.

 

KalyaniKalyani

Its Working fine. Thanks a lot.

This was selected as the best answer