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) {
if (Trigger.isAfter && Trigger.isUpdate) {
updateContactClass obj = new updateContactClass ();
obj.updateContactPhones(Trigger.new); // Calling method to update contacts after account update
}
}
APEX CLASS:
public class updateContactClass {
public void updateContactPhones(List<Account> accountList) {
Set<Id> accountIdSet = new Set<Id>();
List<Contact> conList = new List<Contact>();
// Collecting account IDs to query related contacts
for (Account acc : accountList) {
accountIdSet.add(acc.Id); // Add account Ids to the set
}
// Querying accounts with their related contacts in bulk
List<Account> accountsWithContacts = [SELECT Id, Phone, (SELECT Id, Phone FROM Contacts)
FROM Account
WHERE Id IN :accountIdSet];
// Prepare a map to store accountId -> Phone number
Map<Id, String> accountPhoneMap = new Map<Id, String>();
for (Account acc : accountsWithContacts) {
// Map the account ID to its phone number
accountPhoneMap.put(acc.Id, acc.Phone);
}
// Now process the contacts in bulk without nested loops
for (Contact con : [SELECT Id, Phone, AccountId FROM Contact WHERE AccountId IN :accountIdSet]) {
// If the contact's AccountId exists in the map, update the contact's phone
if (accountPhoneMap.containsKey(con.AccountId)) {
con.Phone = accountPhoneMap.get(con.AccountId); // Update contact phone
conList.add(con); // Add to the list for bulk DML operation
}
}
// Performing the update operation only if there are contacts to update
if (!conList.isEmpty()) {
try {
update conList; // Bulk DML update
} catch (DmlException e) {
// Handle DML exception if needed (e.g., logging the error)
System.debug('Error during update: ' + e.getMessage());
}
}
}
}
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.
DeleteCode is updated now
Delete