+ Start a Discussion
syam11syam11 

trigger when ever Email/ phone of the account is updated ,all the contact email should be same

HI all
   Im new to salesforce . i want to write  a trigger  when ever Email/ phone of the account  is updated ,all the contact email should be same. any one help me to solve 

Thank you
Harsha
Best Answer chosen by syam11
sunny522sunny522
trigger SameEmailOnAllContacts on Account (after update) {
    Set<Id> setAccountId = new Set<Id>();
    for(Account acc:trigger.new) {
        if(Trigger.oldMap.get(acc.ID).Email__c != acc.Email__c || Trigger.oldMap.get(acc.ID).phone != acc.phone) {
            setAccountId.add(acc.id);
        }
    }
    List<Contact> lstContact = new List<Contact>();
    for(Account acc:[Select id,Email__c,(select id,Email from Contacts) from Account where Id in:setAccountId]) {
        for(Contact con:acc.contacts) {
            if(con.Email != acc.Email__c) {
                con.Email = acc.Email__c;
                lstContact.add(con);
            }
        }
    }
    if(lstContact.size() >0) {
        update lstContact;
    }
}

Please use this trigger code Harsha .

All Answers

Boss CoffeeBoss Coffee
To clarify, whenever an Account's email or phone is updated/changed, you want all related Contacts to have their email be the same?
syam11syam11
 when ever Email/ phone of the account  is updated ,all the related contact email should be same 
 
sunny522sunny522
trigger SameEmailOnAllContacts on Account (after update) {
    Set<Id> setAccountId = new Set<Id>();
    for(Account acc:trigger.new) {
        if(Trigger.oldMap.get(acc.ID).Email__c != acc.Email__c || Trigger.oldMap.get(acc.ID).phone != acc.phone) {
            setAccountId.add(acc.id);
        }
    }
    List<Contact> lstContact = new List<Contact>();
    for(Account acc:[Select id,Email__c,(select id,Email from Contacts) from Account where Id in:setAccountId]) {
        for(Contact con:acc.contacts) {
            if(con.Email != acc.Email__c) {
                con.Email = acc.Email__c;
                lstContact.add(con);
            }
        }
    }
    if(lstContact.size() >0) {
        update lstContact;
    }
}

Please use this trigger code Harsha .
This was selected as the best answer