Skip to main content
7 of 7
Fixing code formatting
Derek F
  • 64.1k
  • 15
  • 55
  • 104
trigger preventAccountDeletion on Account (before delete) {
    // Check if the trigger is before delete
    if (Trigger.isBefore && Trigger.isDelete) {
        // Query for account IDs that have related contacts
        List<AggregateResult> accountWithContact = [
            SELECT AccountId
            FROM Contact
            WHERE AccountId IN :Trigger.oldMap.keySet()
            GROUP BY AccountId
            HAVING COUNT(Id) > 0
        ];

        // Throw an error if there are accounts with related contacts
        if (accountWithContact.size() > 0) {
            Trigger.old[0].addError(accountWithContact.size() + ' Accounts cannot be deleted because they have related contacts.');
        }
    }
}