Hey guys, today in this post we are going to learn about how to Write apex trigger on custom Parent Object (Parent__c) to update the related Child Object (Child__c) Phone whenever account Phone is Updated in Salesforce.
You can create an Apex trigger on the Parent__c object that runs after update. The trigger should check if the Phone field has changed, query for the related Child__c records, and then update their Phone field with the new account phone number.
Create Apex Trigger β
Step 1:- Create Apex Controller : parentTrigger.apxt
SFDX:Create Apex Trigger>> New >> parentTrigger.apxt
parentTrigger.apxt [Apex Trigger]
|
|
TRIGGER parentTrigger ON Parent__c (BEFORE INSERT, after INSERT, BEFORE UPDATE, after UPDATE, BEFORE DELETE, after DELETE) {
//WRITE apex TRIGGER TO UPDATE the related Contacts Phone whenever account Phone IS updated
IF(TRIGGER.isBefore){
}ELSE IF(TRIGGER.isAfter){
IF(TRIGGER.isUpdate){
Set<Id> setId = NEW Set<Id>();
Map<Id, String> parentPhoneMap = NEW Map<Id, String>();
FOR(Parent__c p1:TRIGGER.new){
Parent__c oldParent = TRIGGER.oldMap.get(p1.Id);
IF(p1.Phone__c != oldParent.Phone__c){
setId.add(p1.Id);
parentPhoneMap.put(p1.Id, p1.Phone__c);
}}List<Child__c> conObjList = [SELECT Id, Phone__c, Parent__c FROM Child__c WHERE Parent__c IN:setId];
List<Child__c> childItem = NEW List<Child__c>();
FOR(Child__c c1:conObjList){
String newPhone = parentPhoneMap.get(c1.Parent__c);
IF(c1.Phone__c != newPhone){
c1.Phone__c = newPhone;
childItem.add(c1);
}}IF(!childItem.isEmpty()){
UPDATE childItem;}}}}
Further post that would you like to learn in Salesforce
What is the after update trigger?
An AFTER UPDATE trigger is a type of trigger that executes after an UPDATE statement is performed on the table. This article provides a complete guide on how to create and use AFTER UPDATE triggers in MySQL including detailed examples and best practices.
How are contacts and accounts related in Salesforce?
The relationship rules are still simple. Every contact needs to be directly associated with an account. This is the account that appears in Account Name and is usually the company the contact is most closely associated with. Any other accounts associated with the contact represent indirect relationships.
What is the difference between trigger before update and after update?
A BEFORE triggered action executes before the triggering statement , that is, before the occurrence of the trigger event. An AFTER triggered action executes after the action of the triggering statement is complete.
Related Topics | You May Also Like
|
π Get Free Course β
π Salesforce Administrators π Salesforce Lightning Flow Builder π Salesforce Record Trigger Flow Builder |
π Get Free Course β |



