Skip to main content
5 of 7
added 181 characters in body

///Note: Salesforce has built in validation rule to prevent deletion Accounts with related Contacts/ Opportunities.
///Another option is to use Record triggered flow

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.');
    }
  }
}