Play Games

Search This Blog

Saturday, December 26, 2015

Update all contacts phone number with associated account's phone number when associated account is updated

Assume Phone field of Account and Phone field of contact are used here in example.
Sample Code:
trigger updatePhone on Account (after update) {
    Set <Id> accountIdSet = new Set <Id>();
    Map <Id,String> accountMap = new Map <Id,string> ();
    for(Account acc:trigger.new) {
        if(Trigger.oldMap.get(acc.Id).phone != acc.phone) {
            accountIdSet.add(acc.id);
        }
        if(acc.phone != null) {
            accountMap.put(acc.id,acc.phone);
        }
    }
    List <contact> contactList = new List <Contact>();
    for(Contact con:[select id,accountId,Phone from contact where accountId in:accountIdSet]) {
        if(accountMap != null && accountMap.containsKey(con.accountId)) {
            con.phone = accountMap.get(con.accountId);
            contactList.add(con);
        }
    }
    if(contactList.size() >0) {
        update contactList;
    }
}
Output:


1 comment:

  1. Thanks bro i had faced one interview he asked how to update master field with child fields.so i am confusing.but when i seen your blog,i am so HAPPY. Thanks

    ReplyDelete