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
2 risposte