Home > apex > How to lookup Email based on given User name (not current user)

How to lookup Email based on given User name (not current user)

June 13Hits:5
Advertisement

I am trying to populate the custom Email field of all the records of the account object. Based on a custom field MName which is a lookup to the User object, do a lookup to the User object and get the email and populate the email__c in the Account object. I need this bulkified because there can be many account records to do this on.

Here is what I have attempted but am very new so this may be very far from where I want to be.

Thanks

    for(Account acc :Trigger.New)  {     List<User> users = New List<User>();     for(User currUser : users)      {         if (currUser.MName == acc.Name)         {             acc.Email = currUser.Email;         }     }    } 

Answers

Try the below code hope this helps you :

else you can create a formula field as suggested by @Poet

Set<Id> setuserId = new Set<Id>();
Map<Id, Email> mapUserIdToEmail = new Map<Id, Email>();
List<Account> lstAccount = new List<Account>();
for(Account objAcc : Trigger.new){
    if(objAcc.MName__c != null)
        setuserId.add(objAcc.MName__c);
}

for(User objUser : [SELECT Id, Email FROM User WHERE Id IN : setuserId]){
    mapUserIdToEmail.put(objUser.Id, objUser.Email);
}   

for(Account objAcc : Trigger.new){
    if(mapUserIdToEmail.containsKey(objAcc.MName__c))
        lstAccount.add(new Account(Id = objAcc.Id, email__c = mapUserIdToEmail.get(objAcc.MName__c)));
}

update lstAccount;

Tags:trigger, apex

Related Articles

Copyright (C) 2018 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.603 s.