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.


    for(Account acc :Trigger.New)
    List<User> users = New List<User>();
    for(User currUser : users) 
        if (currUser.MName == acc.Name)
            acc.Email = currUser.Email;
  • Your question heading says(not current user) and in your code you are doing some curruser, the question is not clear
    – Jarvis
    Feb 23 '16 at 9:09
  • 1
    To me, wouldn't you be better off using a Formula field? You could literally use a Formula field that would look at the MName__c field (your lookup to the User object) and return the e-mail address of the User? This would do what you want it to do, but also email__c would manage itself and you wouldn't need a Batch class or something to populate existing Account records.
    – Dan Jones
    Feb 23 '16 at 9:13
  • Good point but I am looking for the code itself.
    – Apex N-u-b
    Feb 23 '16 at 12:03

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)

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

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

update lstAccount;
  • Looks good. I will have to try it out. Many thanks
    – Apex N-u-b
    Feb 23 '16 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.