If you want to add an error when you are trying to delete account than you need to
- Retrieve all related contacts
Retrieve all related contacts
- Loop through each contact and add AccountId to Set
Loop through each contact and add AccountId to Set
- Loop through accounts and add an error if account contains any contact
Loop through accounts and add an error if account contains any contact
trigger Account on Account (before delete) { if (Trigger.isBefore && Trigger.isDelete) { List<Contact> 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'); } } } }
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');
}
}