Scenario 1: A company wants to prevent the deletion of Account records that have related Opportunities. How would you implement this using a trigger?
You can achieve this by writing a ‘before delete’ trigger on the Account object. The trigger would check for related Opportunities for each Account being deleted. If related Opportunities are found, the trigger would add an error to the Account record, preventing its deletion.
trigger PreventAccountDeletion on Account (before delete) {
List<Id> accountIds = new List<Id>();
for(Account acc : Trigger.old) {
accountIds.add(acc.Id);
}
Map<Id, AggregateResult> relatedOpps = new Map<Id, AggregateResult>(
[SELECT AccountId, COUNT(Id) oppCount FROM Opportunity WHERE AccountId IN :accountIds GROUP BY AccountId]
);
for(Account acc : Trigger.old) {
if(relatedOpps.containsKey(acc.Id) && (Integer)relatedOpps.get(acc.Id).get(‘oppCount’) > 0) {
acc.addError(‘Cannot delete Account with related Opportunities.’);
}
}
}