Hey guys, today in this post we are going to learn about How to write Apex Trigger to update Account phone from Contact Phone based on lookup relationship in Salesforce.
Final Output β
Other related post that would you like to learn in Salesforce
Create Apex Trigger β
Step 1:- Create Apex Controller : ContactTrigger.apxt
SFDX:Create Apex Trigger>> New >> ContactTrigger.apxt
ContactTrigger.apxt [Apex Trigger]
TRIGGER ContactTrigger ON Contact (BEFORE INSERT, after INSERT) {
IF(TRIGGER.isBefore){
}ELSE IF(TRIGGER.isAfter){
ContactTriggerHandler.conRelAcc(TRIGGER.new);
}
}
Create Trigger Handler Controller β
Step 2:- Create Apex Controller : ContactTriggerHandler.apxc
SFDX:Create Apex Trigger>> New >> ContactTriggerHandler.apxc
ContactTriggerHandler.apxc [Trigger Handler]
public class ContactTriggerHandler {
public static void conRelAcc(List<Contact> conList){
Map<Id, Contact> conMap = NEW Map<Id, Contact>();
FOR(Contact con:conList){
conMap.put(con.AccountId,con);
}
List<Account> accObjItem = NEW List<Account>();
List<Account> accObjList = [SELECT Id, Name, Phone FROM Account WHERE Id IN:conMap.keySet()];
FOR(Account acc:accObjList){
acc.Phone = conMap.get(acc.Id).Phone;
accObjItem.add(acc);
}
IF(!accObjItem.isEmpty()){
UPDATE accObjItem;
}
}
}
Further post that would you like to learn in Salesforce
What is the difference between before update and after update trigger?
Before Triggers are ideal for making changes to the triggering record, while After Triggers are suitable for working with related records and system-generated field values. Understanding this distinction is key to designing effective and efficient trigger logic in Salesforce.
What will happen if you try to update record in after trigger context?
If we perform update operation on the record in after update event logic recursive triggers will arise. Using static Boolean variable in an apex class (we should not keep static Boolean variable inside of the trigger) we can avoid recursive triggers.
What is the account contact relationship record?
In Salesforce, an Account-Contact Relationship refers to the association between an Account record (representing companies or organizations) and a Contact record (representing individuals).
Related Topics | You May Also Like
Our Free Courses β
π Get Free Course β
π Salesforce Administrators π Salesforce Lightning Flow Builder π Salesforce Record Trigger Flow Builder |
π Get Free Course β
π Aura Lightning Framework π Lightning Web Component (LWC) π Rest APIs Integration |