You need to sign in to do that
Don't have an account?
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);
}
}
}
}
Its Working fine. Thanks a lot.
All Answers
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.
No nothing is updating for me. So any sugesstions on what the query should be?
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.
Its Working fine. Thanks a lot.