Apex triggers are powerful tools in Salesforce that allow developers to perform custom actions before or after events to Salesforce records, such as insertions, updates, or deletions. Triggers are essential for automating complex business processes and ensuring data integrity. In this blog post, we will explore several practical scenarios for using Apex triggers, complete with easy-to-understand examples.
1. Before Insert Trigger: Ensure Unique Email Addresses
Scenario: You want to ensure that no two contacts have the same email address in your Salesforce org.
Trigger:
trigger CheckUniqueEmail on Contact (before insert) { Set<String> emailSet = new Set<String>(); for (Contact con : Trigger.new) { if (con.Email != null) { emailSet.add(con.Email); } } List<Contact> existingContacts = [SELECT Email FROM Contact WHERE Email IN :emailSet]; Map<String, Contact> emailMap = new Map<String, Contact>(); for (Contact con : existingContacts) { emailMap.put(con.Email, con); } for (Contact con : Trigger.new) { if (con.Email != null && emailMap.containsKey(con.Email)) { con.addError('This email address is already in use.'); } } }
2. After Insert Trigger: Create a Welcome Task
Scenario: After a new contact is inserted, create a task to follow up with the new contact.
Trigger:
trigger CreateWelcomeTask on Contact (after insert) { List<Task> tasks = new List<Task>(); for (Contact con : Trigger.new) { Task t = new Task(); t.Subject = 'Follow up with ' + con.FirstName + ' ' + con.LastName; t.WhoId = con.Id; t.OwnerId = con.OwnerId; t.Status = 'Not Started'; tasks.add(t); } insert tasks; }
3. Before Update Trigger: Prevent Field Changes Based on Criteria
Scenario: Prevent changes to the Email
field if the contact's status is "Active".
Trigger:
trigger PreventEmailChange on Contact (before update) { for (Contact con : Trigger.new) { Contact oldCon = Trigger.oldMap.get(con.Id); if (oldCon.Status__c == 'Active' && con.Email != oldCon.Email) { con.Email.addError('Email address cannot be changed for active contacts.'); } } }
4. After Update Trigger: Update Related Records
Scenario: When an Account's rating changes, update a custom field on all related contacts.
Trigger:
trigger UpdateRelatedContacts on Account (after update) { List<Contact> contactsToUpdate = new List<Contact>(); for (Account acc : Trigger.new) { Account oldAcc = Trigger.oldMap.get(acc.Id); if (acc.Rating != oldAcc.Rating) { List<Contact> relatedContacts = [SELECT Id, AccountId, CustomRating__c FROM Contact WHERE AccountId = :acc.Id]; for (Contact con : relatedContacts) { con.CustomRating__c = acc.Rating; contactsToUpdate.add(con); } } } update contactsToUpdate; }
5. Before Delete Trigger: Prevent Deletion Based on Criteria
Scenario: Prevent deletion of accounts that have an active opportunity.
Trigger:
trigger PreventAccountDeletion on Account (before delete) { Set<Id> accountIds = Trigger.oldMap.keySet(); List<Opportunity> activeOpps = [SELECT Id, AccountId FROM Opportunity WHERE AccountId IN :accountIds AND IsClosed = false]; if (!activeOpps.isEmpty()) { Trigger.old[0].addError('Accounts with active opportunities cannot be deleted.'); } }
Conclusion
Apex triggers provide a robust way to automate and enforce business logic in Salesforce. By understanding and utilizing triggers, you can ensure data integrity, automate processes, and enhance your Salesforce org's functionality. The scenarios presented in this post are just the beginning. With practice, you can create more complex and tailored triggers to meet your organization's needs. Happy coding!
0 Comments