APEX Trigger Learning
Table of Contents
1. Updating Billing Address
2. Sending Email on Account Creation
3. Validating Unique Account Names
4. Updating Related Opportunities
5. Deleting Child Contacts on Account Deletion
Scenario 1 : Updating Billing Address
Description: This scenario triggers before an update on the Account object. It checks if
Billing Address fields have changed and updates the records accordingly in a bulkified
manner.
Event: Trigger.isBefore, Trigger.isUpdate
DMLs: Database.update
Context Variables: Trigger.isBefore, Trigger.isUpdate, Trigger.new, Trigger.oldMap
Database Methods: Database.update
System Variables: None used in this scenario.
CODE
public class AccountTriggerHandler {
public void updateBillingAddress(List<Account> newAccounts, Map<Id, Account> oldMap) {
List<Account> accountsToUpdate = new List<Account>();
for (Account newAcc : newAccounts) {
// Check if Billing Address field has changed
if (!Objects.equals(newAcc.BillingStreet, oldMap.get(newAcc.Id).BillingStreet) ||
!Objects.equals(newAcc.BillingCity, oldMap.get(newAcc.Id).BillingCity) ||
!Objects.equals(newAcc.BillingState, oldMap.get(newAcc.Id).BillingState) ||
!Objects.equals(newAcc.BillingPostalCode, oldMap.get(newAcc.Id).BillingPostalCode) ||
!Objects.equals(newAcc.BillingCountry, oldMap.get(newAcc.Id).BillingCountry)) {
accountsToUpdate.add(newAcc);
}
}
if (!accountsToUpdate.isEmpty()) {
// Perform DML operation to update records with changed Billing Address
Database.update(accountsToUpdate);
}
}
APEX Trigger Learning
Scenario 2 : Sending Email on Account Creation
Description: This scenario triggers after an Account is inserted. It constructs and sends
an email notification for each newly created Account.
Event: Trigger.isAfter, Trigger.isInsert
DMLs: None used in this scenario.
Context Variables: Trigger.isAfter, Trigger.isInsert, Trigger.new
Database Methods: None used in this scenario.
System Variables: None used in this scenario.
public class AccountTriggerHandler {
public void sendEmailOnCreation(List<Account> newAccounts) {
List<Messaging.SingleEmailMessage> emailMessages = new
List<Messaging.SingleEmailMessage>();
for (Account newAcc : newAccounts) {
// Your logic to build email content and recipients
Messaging.SingleEmailMessage email = new
Messaging.SingleEmailMessage();
email.setToAddresses(new List<String>{'
[email protected]'});
email.setSubject('New Account Created: ' + newAcc.Name);
email.setPlainTextBody('A new Account was created. Check it
out!');
emailMessages.add(email);
// Send emails
Messaging.sendEmail(emailMessages);
}
}
APEX Trigger Learning
Scenario 3 : Validating Unique Account Names
Description: This scenario triggers before an insert on the Account object. It validates
that no two Accounts have the same name.
Event: Trigger.isBefore, Trigger.isInsert
DMLs: None used in this scenario.
Context Variables: Trigger.isBefore, Trigger.isInsert, Trigger.new
Database Methods: Database.query, Database.saveResult
System Variables: None used in this scenario.
//Validating Unique Account Names
public class AccountTriggerHandler {
public void validateUniqueNames(List<Account>
newAccounts) {
Set<String> existingAccountNames = new Set<String>();
for (Account acc : [SELECT Name FROM Account WHERE
Name IN :newAccounts]) {
existingAccountNames.add(acc.Name);
}
for (Account newAcc : newAccounts) {
if (existingAccountNames.contains(newAcc.Name)) {
newAcc.addError('Account with the same name already
exists.');
}
}
}
}
APEX Trigger Learning
Scenario 4 : Updating Related Opportunities
Description: This scenario triggers after an update on the Account object. It updates
related Opportunities based on changes in the Account.
Event: Trigger.isAfter, Trigger.isUpdate
DMLs: Database.update
Context Variables: Trigger.isAfter, Trigger.isUpdate, Trigger.new, Trigger.oldMap
Database Methods: Database.update
System Variables: None used in this scenario.
//Updating Related Opportunities
public class AccountTriggerHandler {
public void updateRelatedOpportunities(List<Account> newAccounts, Map<Id,
Account> oldMap) {
List<Opportunity> opportunitiesToUpdate = new List<Opportunity>();
for (Account newAcc : newAccounts) {
// Your logic to update related Opportunities
// For example, updating Opportunities with a specific field based on
changes in the Account
List<Opportunity> relatedOpportunities = [SELECT Id, Name FROM
Opportunity WHERE AccountId = :newAcc.Id];
for (Opportunity opp : relatedOpportunities) {
// Your logic to update Opportunities
// For example, updating Opportunity fields based on changes in the
Account
opp.Name = 'Updated Opportunity Name';
opportunitiesToUpdate.add(opp);
}
}
if (!opportunitiesToUpdate.isEmpty()) {
// Perform DML operation to update related Opportunities
Database.update(opportunitiesToUpdate);
}
}
}
APEX Trigger Learning
Scenario 5 : Deleting Child Contacts on Account Deletion
Description: This scenario triggers before an Account is deleted. It identifies child
Contacts associated with the Account and deletes them.
Event: Trigger.isBefore, Trigger.isDelete
DMLs: Database.delete
Context Variables: Trigger.isBefore, Trigger.isDelete, Trigger.old
Database Methods: Database.delete
System Variables: None used in this scenario.
//Deleting Child Contacts on Account Deletion
public class AccountTriggerHandler {
public void deleteChildContactsOnAccountDelete(List<Account> oldAccounts)
{
Set<Id> accountIdsToDeleteContacts = new Set<Id>();
for (Account oldAcc : oldAccounts) {
accountIdsToDeleteContacts.add(oldAcc.Id);
}
List<Contact> contactsToDelete = [SELECT Id FROM Contact WHERE
AccountId IN :accountIdsToDeleteContacts];
if (!contactsToDelete.isEmpty()) {
// Perform DML operation to delete child Contacts
Database.delete(contactsToDelete);
}
}
}
APEX Trigger Learning
Main Trigger Class (AccountMasterTrigger.cls)
Description: Handles various scenarios for the Account
object.
Best Practices:
Bulkification: Methods handle collections for bulk
operations.
Separation of Concerns: Triggers lightweight; logic
delegated to handler.
Descriptive Method Names: Clearly named methods
for better readability.
Context Variables: Leveraging context variables for
context-aware operations.
Error Handling: Proper error handling mechanisms
implemented.
Avoid SOQL Queries in Loops: Code bulkified to avoid
queries inside loops.
Email Sending: Email logic in a separate utility class or
integration.
APEX Trigger Learning
Main Trigger: AccountMasterTrigger
// Main Trigger Code
trigger AccountMasterTrigger on Account (before insert, after insert,
before update, after update, before delete, after delete) {
AccountTriggerHandler handler = new AccountTriggerHandler();
if (Trigger.isBefore) {
if (Trigger.isInsert) {
handler.sendEmailOnCreation(Trigger.new);
handler.validateUniqueNames(Trigger.new);
}
if (Trigger.isUpdate) {
handler.updateBillingAddress(Trigger.new, Trigger.oldMap);
handler.updateRelatedOpportunities(Trigger.new,
Trigger.oldMap);
}
if (Trigger.isDelete) {
handler.deleteChildContactsOnAccountDelete(Trigger.old);
}
}
if (Trigger.isAfter) {
if (Trigger.isInsert) {
// Additional logic after Account insertion
}
if (Trigger.isUpdate) {
// Additional logic after Account update
}
if (Trigger.isDelete) {
// Additional logic after Account deletion
APEX Trigger Learning
}
}
}