Hey guys, today in this post we are going to learn about How to Write a Apex trigger to Add the Contact First Name and Last Name to Account Custom Field Whenever the Contact inserted or Updated in Salesforce.
➡ Real time scenarios:- Write a trigger on Contact and Add First Name and Last Name of Contact to Associated Account Custom Field Whenever Contact record is Inserted or Updated.
Files we used in this post example
ContactAccountTrigger.apxt | Apex Class Trigger | It will be fired whenever Contact Record is inserted Or updated |
Parent Object:- Account |
Parent Object (Account) | Trigger on Contact and updae the Associted Account Custom Field (updateContact__c) |
Child Object:- Contact |
Child Object (Contact) | It is child object and associated with Account Object. |
Final Output
Other related post that would you like to learn.
Step 1:- Create Apex Class : ContactAccountTrigger.apxt
From Developer Console >> File >> New >> Apex Class
ContactAccountTrigger.apxt [Apex Class Controller]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
trigger ContactAccountTrigger on Contact (before insert, before update, after insert, after update) { List<Contact> conList =new List<Contact>(); Set<Id> setid = new Set<Id>(); if(trigger.isBefore){ system.debug('trigger before event'); conList = trigger.new; }else if(trigger.isAfter){ conList=trigger.new; for(Contact con:conList){ setid.add(con.AccountId); } system.debug('setid ' + setid); List<Account> accList = [Select Id, Name, updateContact__c From Account Where Id=:setid]; if(trigger.isInsert){ for(Contact c1:trigger.new){ for(Account a1:accList){ a1.updateContact__c= c1.FirstName + ' ' + c1.LastName; update a1; } } }else if(trigger.isUpdate){ for(Contact c2:trigger.new){ for(Account a2:accList){ a2.updateContact__c= c2.FirstName + ' ' + c2.LastName; update a2; } } } } } |
Other post that would you like to learn in LWC
Further post that would you like to learn