AFTER UPDATE:
This event runs the block of code after the updated data is
committed to the database. Operations such as creating or updating related records
can be performed under this event.
SYNTAX:
trigger triggerName on objectName (after
update) {
// Block of code
}
SCENARIO:
We are having the requirement that when an account record is
updated, we need to update all related contact record phone number field with
the Account phone number.
APEX TRIGGER:
trigger AccountMainTrigger on Account (after update) { // Specifying the event.
createContactClass obj=new
createContactClass(); // Declaring
the instance of the class.
if(trigger.isafter &&
trigger.isupdate) // Using
context variables.
{
obj.method1(trigger.new); //calling apex class method
}
}
APEX CLASS:
public class createContactClass {
List<contact> conList=new
List<contact>();
set<id> accountIdSet=new
set<id>();
public void method1(List<Account>
accountList){ // Getting
list of account records.
for(Account obj:accountList){
accountIdSet.add(obj.id); // Getting id's of account in set.
}
for(Account obj:[Select
id,Name,phone,(Select id,phone from Contacts) from Account where id
in:accountIdSet]){ // Querying
Account with its related contacts.
for(contact con:obj.Contacts){ // Getting contact list for a
particular account and iterating over it to update phone on all contact records
with phone from that particular account.
con.phone=obj.phone; // Updating the phone on the
contact record from account.
conList.add(con); // Adding updated contacts in the
list to perform DML operation over it.
}
}
if(conList.size() > 0){ // Checking if the list contains an
element.
update conList; // Updating contacts.
}
}
}
Now let us update the phone number on account record to see
the results,
Before updating the
Account record,
After updating the Account record with different phone
number,
This is a very Bad example. For loop inside for loop
ReplyDeleteI think the example is okay but this nested for loop and inner query is a bad usage. We could avoid this using maps effectively. The requirement also should compare old and new values of account phone number, instead this code runs every time anything on account record gets updated.
Delete