Scenario: 4
As a Salesforce developer, you're tasked with implementing a trigger to enforce a validation rule on the Account object. The requirement is to prevent the deletion of an Account record if it has related Opportunity records with a stage of 'Closed Won'. Additionally, when an Account is deleted, all related Opportunity records should be deleted as well. How would you approach this scenario using Apex triggers?
Code:
// Trigger: PreventAccountDeletionTrigger
// Object: Account
// Purpose: Prevent deletion of Accounts with related 'Closed Won' Opportunities and delete related Opportunities when an Account is deleted
trigger PreventAccountDeletionTrigger on Account (before delete) {
// Method to prevent deletion of Accounts with related 'Closed Won' Opportunities
public static void preventAccountDeletion(List<Account> accountsToDelete, Map<Id, Account> oldMap) {
// Collection to store Account IDs with 'Closed Won' Opportunities
Set<Id> accountIdsWithClosedWonOpportunities = new Set<Id>();
// Query for related 'Closed Won' Opportunities
for (Opportunity opp : [SELECT Id, AccountId, StageName
FROM Opportunity
WHERE AccountId IN :accountsToDelete
AND StageName = 'Closed Won']) {
accountIdsWithClosedWonOpportunities.add(opp.AccountId);
}
// Iterate through Accounts to be deleted and check for related 'Closed Won' Opportunities
for (Account acc : accountsToDelete) {
if (accountIdsWithClosedWonOpportunities.contains(acc.Id)) {
acc.addError('Cannot delete Account with related Opportunities in "Closed Won" stage');
}
}
}
// Method to delete related Opportunities when an Account is deleted
public static void deleteRelatedOpportunities(List<Account> accountsToDelete, Map<Id, Account> oldMap) {
// Collection to store Opportunity IDs to be deleted
List<Opportunity> opportunitiesToDelete = new List<Opportunity>();
// Query for related Opportunities
for (Account acc : accountsToDelete) {
opportunitiesToDelete.addAll([SELECT Id
FROM Opportunity
WHERE AccountId = :acc.Id]);
}
// Delete related Opportunities
delete opportunitiesToDelete;
}
// Trigger handler method
public static void beforeDelete(List<Account> accountsToDelete, Map<Id, Account> oldMap) {
preventAccountDeletion(accountsToDelete, oldMap);
deleteRelatedOpportunities(accountsToDelete, oldMap);
}
}
Evaluation:
- The candidate provides a comprehensive Apex trigger named
PreventAccountDeletionTrigger
that executes before the deletion of Account records. - They effectively use SOQL queries to query related Opportunity records and enforce the validation rule preventing the deletion of Accounts with related 'Closed Won' Opportunities.
- The code also includes logic to delete related Opportunity records when an Account is deleted, ensuring data integrity and consistency.
- The trigger handler method
beforeDelete
calls both thepreventAccountDeletion
anddeleteRelatedOpportunities
methods, maintaining separation of concerns and promoting code maintainability.
0 Comments