Apex Triggers - 90 (Accenture Interview Scenario)
Business Requirement
The business wants to protect important customer data by preventing users from deleting an Active Account if it has one or more related Contact records.
Only users with the System Administrator profile are allowed to delete such accounts. All other users should receive an error message, and the deletion should be blocked.
Scenario Details
ABC Corporation is an active customer in Salesforce. The account contains multiple related contacts, such as John Doe and Jane Smith.
A user attempts to delete the account.
Before Salesforce deletes the record, a Before Delete Apex Trigger is executed.
The trigger performs the following validations:
- Checks whether the Account Status = Active.
- Checks whether the Account has at least one related Contact.
- Checks whether the logged-in user's Profile is System Administrator.
================================================================
trigger AccountDeletionTrigger on Account (before delete) {
// Ensure code runs only during the before delete event
if (Trigger.isBefore && Trigger.isDelete) {
AccountDeletionHandler.preventActiveAccountDeletion(Trigger.old);
}
}
=====================================================================
public class AccountDeletionHandler {
public static void preventActiveAccountDeletion(List<Account> oldAccounts) {
// Step 1: Collect IDs of active accounts being deleted
Set<Id> activeAccountIds = new Set<Id>();
if (oldAccounts != null) {
for (Account acc : oldAccounts) {
// Check if the custom 'Is_Active__c' checkbox is true
if (acc.Is_Active__c == true) {
activeAccountIds.add(acc.Id);
}
}
}
// If no active accounts are being deleted, exit early
if (activeAccountIds.isEmpty()) {
return;
}
// Step 2: Fetch the profile name of the logged-in user
Profile currentUserProfile = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId() LIMIT 1];
// Step 3: Calculate the count of related contacts for each active account
Map<Id, Integer> accountToContactCountMap = new Map<Id, Integer>();
for (Contact con : [SELECT AccountId FROM Contact WHERE AccountId IN :activeAccountIds]) {
if (accountToContactCountMap.containsKey(con.AccountId)) {
accountToContactCountMap.put(con.AccountId, accountToContactCountMap.get(con.AccountId) + 1);
} else {
accountToContactCountMap.put(con.AccountId, 1);
}
}
// Step 4: Apply validation checks and throw error if conditions match
for (Account acc : oldAccounts) {
if (activeAccountIds.contains(acc.Id)) {
Integer contactCount = accountToContactCountMap.containsKey(acc.Id) ? accountToContactCountMap.get(acc.Id) : 0;
// Block deletion if it has at least 1 contact AND the user is NOT a System Administrator
if (contactCount >= 1 && currentUserProfile.Name != 'System Administrator') {
acc.addError('Active accounts with at least one related contact can only be deleted by a System Administrator.');
}
}
}
}
}
==================================================================
Comments
Post a Comment