Hey guys, today in this post we are going to learn about how to write trigger to update account Phone when contact Phone is updated in Salesforce.
A trigger is the piece of code that executed before and after a record is Inserted/Updated/Deleted from the force.com database. Apex can be invoked through the use of triggers. A Trigger is a functional action which gets on particular events. Triggers will happen before records entering into the database and while goint out of the database. To know more details about Apex Trigger, Click Here.
Final Output β
You can download file directly from github by Click Here.
Other related post that would you like to learn in Salesforce
- Find the below steps βΎ
Create Apex Trigger β
Step 1:- Create Apex Trigger : contactToAccountUpdateTrigger.apxt
From Developer Console >> File >> New >> Apex Trigger
contactToAccountUpdateTrigger.apxt [Apex Trigger]
TRIGGER contactToAccountUpdateTrigger ON Contact (BEFORE UPDATE, after UPDATE) {
IF(TRIGGER.isBefore){
system.debug('Event before trigger');
}
ELSE IF(TRIGGER.isAfter){
system.debug('Event after trigger');
IF(TRIGGER.isUpdate){
Map<Id,Contact> conMapItem=NEW Map<Id,Contact>();
FOR(Contact con:TRIGGER.new){
conMapItem.put(con.AccountId,con);
}
List<Account> accObjList=[SELECT Id,Name,Phone,(SELECT Id,AccountId,Name,Phone FROM Contacts) FROM Account WHERE Id IN:conMapItem.keyset()];
IF(accObjList.size()>0){
FOR(Account a:accObjList){
a.Phone=conMapItem.get(a.id).Phone;
}
UPDATE accObjList;
}
}
}
}
Further post that would you like to learn in Salesforce
Can we update record in after trigger?
Yes, you can update records in an after trigger - but you need to give it some thought and make sure it's the right thing to do.
What is trigger oldMap?
A map of IDs to the old versions of the sObject records. Note that this map is only available in the update and delete triggers.
What is the difference between after and before trigger?
Before Trigger is a type of trigger that automatically executes before a certain operation occurs on the table. In contrast, after trigger is a type of trigger that automatically executes after a certain operation occurs on the table.
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 |