Skip to main content
1 of 2

If you want to add an error when you are trying to delete account than you need to

  1. Retrieve all related contacts
  2. Loop through each contact and add AccountId to Set
  3. Loop through accounts and add an error if account contains any contact

List relatedContacts = [SELECT AccountId FROM Contact WHERE AccountId IN : Trigger.oldMap.keySet()];

    Set<Id> accIds = new Set<Id>();
    for (Contact contact : relatedContacts) {
        accIds.add(contact.accountId);
    }

    for (Account account : trigger.old) {
        if (accIds.contains(account.Id)) {
            account.addError('You cannot delete this account');
        }
    }   

enter image description here