Write a trigger to prevent Account deletion if it has one or more related Contacts.
Answer
Use before delete and check for child Contacts with a subquery.
apex
trigger AccountTrigger on Account (before delete) {
for (Account a : [SELECT Id, (SELECT Id FROM Contacts LIMIT 1)
FROM Account WHERE Id IN :Trigger.oldMap.keySet()]) {
if (!a.Contacts.isEmpty()) {
Trigger.oldMap.get(a.Id).addError('Cannot delete an Account that has Contacts.');
}
}
}
Use Trigger.old records for addError in delete triggers. Note that a Contact-Account relationship with a master-detail or restricted delete would behave differently.
apex-triggertriggercodingscenariovalidation