+ Start a Discussion
JkkJkk 

Please help me with a trigger to populate contact's email domain in Account custom field seperated by comma.

Aslam iqbal - SoqlAslam iqbal - Soql
please try below

trigger ContactEmailOnAccount on Contact (after update, after insert) 
{    
   String commaDelimitedEmail;
   Set<id> lstAccIds= new Set<id>();
   for(Contact con : Trigger.new)
   {
    lstAccIds.add(con.accountid);
   }

   List<Account> lstAccUpdate = new List<Account>();
   for(Account acc : [Select id, name, Contact_EmailDomains__c, 
                             (Select Id, name From Contacts) 
                        From Account Where Id In : lstAccIds])
   {
       for(Contact con : acc.contacts)
       {
        if(con.lastname != null)
        {
            commaDelimitedEmail = commaDelimitedEmail + ', ' + con.email.right(con.email.length()-con.email.indexOf('@')-1);
        }
        acc.Contact_EmailDomains__c = commaDelimitedEmail;
    }    
     lstAccUpdate.add(acc);
   }    
   update lstAccUpdate;
}
Ajay K DubediAjay K Dubedi
Hi,
I created a custom field in Account object 'Contact_Email__c' which is long text area type. you can use below code.
//Trigger
trigger UpdateEmail on Contact(before insert, after update) {
   if((Trigger.isBefore && Trigger.isInsert) || (Trigger.isUpdate && Trigger.isAfter)){
        UpdateEmailClass.updateEmailMethod(trigger.new);
   }
}

//Trigger helper class
public class UpdateEmailClass{
    public static void  updateEmailMethod(List<Contact> contactList){
        Set<Id> AccIdSet = new Set<Id>();
        Map<Id,List<String>> accIdVsString = new  Map<Id,List<String>>();
        for(Contact conObj : contactList){
            if(conObj.AccountId != NULL && conObj.Email != NULL){
                AccIdSet.add(conObj.AccountId);
                if(!accIdVsString.containsKey(conObj.AccountId)){
                     accIdVsString.put(conObj.AccountId, new List<String>());
                }
               accIdVsString.get(conObj.AccountId).add(conObj.Email);
            }
        }
        List<Account> accountList = new List<Account>();
        if(AccIdSet.size() > 0){
            accountList = [SELECT Name, Contact_Email__c FROM Account WHERE Id IN: AccIdSet LIMIT 10000];
        }
        if(accountList.size() > 0){
            for(Account accObj : accountList){
                
                    if(accIdVsString.containsKey(accObj.Id)){
                        accObj.Contact_Email__c = accObj.Contact_Email__c+', '+accIdVsString.get(accObj.Id);
                    }
                
            }
        }
        update accountList;
    }
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi