Hey guys, today in this post we are going to learn about How to Update the Associated Contact Account Name is Null Whenever Account Record is Updated in Salesforce Apex Trigger.
Real time scenarios:- Write a trigger on Account and update associated contact Account Name is Null Whenever Account record is Updated.
Files we used in this post example:-
lookupAccountNull.apxt | Apex Class Trigger | It will be fired whenever Account Record is updated |
Parent Cusotm Object:- Account | Parent Object (Account) | Trigger on Parent Object (Account) and updaed the Associted Contact Account Name Null |
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 in Salesforce
Step 1:- Apex Class Trigger : lookupAccountNull.apxt
From Developer Console >> File >> New >> Apex Trigger
lookupAccountNull.apxt [Apex Class Trigger]
TRIGGER lookupAccountNull ON Account (BEFORE INSERT, BEFORE UPDATE, after INSERT, after UPDATE) {
List<Account> AccList =NEW List<Account>();
Map<Id, Account> accMap=NEW Map<Id, Account>();
List<Contact> conAc=NEW List<Contact>();
IF(TRIGGER.isBefore){
system.debug('trigger event before');
AccList=TRIGGER.new;
}ELSE IF(TRIGGER.isAfter){
system.debug('trigger event after');
IF(TRIGGER.isUpdate){
AccList=TRIGGER.new;
system.debug('AccList ' + AccList);
FOR(Account acc:AccList){
FOR(Contact c1:[SELECT Id, Name, FirstName, LastName, AccountId FROM Contact WHERE AccountId=:acc.Id]){
system.debug('c1' + c1);
c1.AccountId=NULL;
conAc.add(c1);
}
}
UPDATE conAc;
}
}
}
Further post that would you like to learn in Salesforce
Can we perform DML operation in before trigger?
Before Trigger: Before triggers are used to perform the logic on the same object and specifically we cannot use the DML operation (Insert, update, delete) on these triggers. These triggers fired before the data saved into the database.
How do you test Apex triggers?
In the Developer Console, click File | New | Apex Trigger. Enter AccountDeletion for the trigger name, and then select Account for the sObject. Click Submit. Replace the default code with the following.
Can we write DML statement in trigger?
Before triggers are used to perform the logic on the same object and it triggers fired before the data saved into the database. For DML operation it required to commit with data base. So, we cannot use the DML operation on these triggers. As per Order of execution before trigger fire and then after trigger fire.
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 |