+ Start a Discussion
Vijay ummedaVijay ummeda 

Trigger to update contact email when account email is updated

Hi Team,

I am trying to write a triiger when an account email is updated i want to update contact email as well. 
can you help me in achevie this from trigger .

trigger accountemailupdated on account(before insert,before update){
List<account> emailnew = new List<account>();
set<id> idvalue = new set<id>();
{
for(account a : trigger.new){
idvalue.add(a);
}
emailnew = [select id,name,email (select id,email from contacts) form account where account id in:idvalue]

for(contacts c :emailnew.accountid){
contacts con = new contacts();
if(emailnew.accountid==con.accountid)
{
con.email = emailnew.email;
}
update emailnew;
}
    
 
SwethaSwetha (Salesforce Developers) 
HI Vijay,
What is the challenge you are facing with the code you provided?
Related:https://salesforce.stackexchange.com/questions/117600/trigger-on-account-to-update-contactwhenever-account-billingaddress-is-updated
Malika Pathak 9Malika Pathak 9

Hi Vijay,

Please Find The Solution. Trigger to update contact email when account email is updated.

trigger AccountTrigger on Account (after update) {
    
    
    if(trigger.isAfter && trigger.isUpdate){
        system.debug('inside');
        set<Id> setId=new set<Id>();
        for(Account ac:trigger.new){
            if(ac.Email__c!=NULL){
                setId.add(ac.id);
            }
        }
        
        List<Contact> contactList=new List<Contact>([select id,accountid,Email from contact where accountid in: setId]);
        map<Id,Account> accountMap=new map<Id,Account>([select id,Email__c from Account where id in: setId]);
        system.debug('contactList '+contactList);
        for(Contact con:contactList){
            if(con.accountid==accountMap.get(con.AccountId).id){
                CON.Email=accountMap.get(con.AccountId).detail__c;
            }
        }
        update contactList;
    }
    
}


Please Let me know it is working or not.

Please mark best answer so that other people would take reference from it.

Thanks