Trigger to update related records based on changes in Parent record

Requirement: Whenever, phone number gets updated in Account object, all the related Contacts should also be updated with same phone number.

Solution: This can be achieved by using Trigger.

Account "Test Account" has two contacts and phone numbers are highlighted for both Accounts and Contacts.


Changing Phone number of "Test Account" to 5555555555 and same will be updated to both contacts.




Trigger:
//Creating a Trigger on "before Update" event.

Trigger AccConUpd on Account (before Update) {
               map<id,account> accdtl = new map<id,account>();
  
              //For loop based on number of records in Trigger.New.
              //It will check if the phone field has changed or not 
              //because trigger will execute even if some other fields 
              //gets updated in Account object.
  
              for(integer i=0;i<trigger.new.size();i++) {
                       if(trigger.old[i].phone != trigger.new[i].phone) {
                          accdtl.put(trigger.old[i].id, trigger.new[i]);
                        }  
               }
            //Creating list for Contact object and updating the phone 
            //field based on Account object's phone field.
  
           list<contact> updcont = new list<contact>();
           for(contact c: [select accountid, phone from contact 
                 where accountid in :accdtl.keyset()]) {
                       account accupd = accdtl.get(c.accountid);
                       c.phone = accupd.phone;
                       updcont.add(c);
             }
     update updcont;
}

Cheers!

Comments

  1. SOQL inside of the for loop , not good

    ReplyDelete
    Replies
    1. this is a SOQL for-loop, which is okay and often optimal. It is different than having SOQL inside of a for-loop
      https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_loops_for_SOQL.htm

      Delete
  2. I think instead of trigger we can able to built the same functionality using Process Builder and it's very easy :)

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular Posts