Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have a custom field in Account, AccountPhone which after update must copy its phone values to child Contacts standard field Phone. Following is what I tried unsuccessfully...

trigger copyPhone2Contacts on Account (before update, after update) {

Contact[]con=[select Phone from Contact where Account in:Trigger.new];
for(Contact c :con){

c.Phone=Trigger.newMap.get(c.AccountPhone__c);
}
 update con;
}

Any help or suggestion will be appreciated. Thanks.

share|improve this question

1 Answer 1

up vote 5 down vote accepted

Here is what I would do:

trigger CopyAccountPhoneToContactPhones on Account (after update) {
    Map<Id, String> m = new Map<Id, String>();
    for (Account a : Trigger.new) {
        Account old = Trigger.oldMap.get(a.Id);
        // Only want the expensive and governor limited Contact SOQL/DML for this change
        if (a.AccountPhone__c != old.AccountPhone__c) {
            m.put(a.Id, a.AccountPhone__c);
        }
    }
    if (m.size() > 0) {
        Contact[] contacts = [
                select Id, AccountId
                from Contact
                where AccountId in :m.keySet()
                ];
        for (Contact c : contacts) {
            c.Phone = m.get(c.AccountId);
        }
        update contacts;
    }
}
share|improve this answer
    
Thanks for replying @keith-c . I tried your code but got a compiler error expecting a semi colon at for (Contact c : contacts) { –  MnZ May 27 at 12:14
    
I'm sorry. Forgot to add ; after Contact[] contacts = [ select Id, AccountId from Contact where AccountId in :m.keySet() ] –  MnZ May 27 at 12:15
    
I've changed it now - try the current code. –  Keith C May 27 at 12:15
    
....and working perfectly. Thanks –  MnZ May 27 at 12:16
    
I have one question. What is the purpose of c.Phone = m.get(c.AccountId); statement? –  MnZ May 27 at 16:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.