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.
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:
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()]) {
where accountid in :accdtl.keyset()]) {
account accupd = accdtl.get(c.accountid);
c.phone = accupd.phone;
updcont.add(c);
}
update updcont;
}
Cheers!
SOQL inside of the for loop , not good
ReplyDeletethis is a SOQL for-loop, which is okay and often optimal. It is different than having SOQL inside of a for-loop
Deletehttps://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_loops_for_SOQL.htm
So easy example
ReplyDeleteI think instead of trigger we can able to built the same functionality using Process Builder and it's very easy :)
ReplyDeleteyes i agree
ReplyDeleteThis comment has been removed by the author.
ReplyDelete