Saturday, July 27, 2024

Trigger to prevent deletion of account if it has associated contact in salesforce

The PrevAccountDeletion trigger on the Account object is designed to prevent the deletion of any account that has associated contacts. It runs before the account deletion operation. The trigger collects the IDs of the accounts being deleted and checks for associated contacts by querying the Contact object. If any account has associated contacts, it adds an error message to the account record, stopping the deletion process. This ensures that accounts with related contacts cannot be removed, maintaining data integrity within the Salesforce system.

trigger PrevAccountDeletion on Account (before delete) {

    // Hold IDs of accounts that have associated contacts

    Set<Id> accountIdsWithContacts = new Set<Id>();

    // IDs of accounts being deleted

    Set<Id> accountIdsToDelete = Trigger.oldMap.keySet();

    // Find contacts associated with the accounts being deleted

for (Contact contact : [SELECT AccountId FROM Contact WHERE AccountId IN :accountIdsToDelete]) {

        accountIdsWithContacts.add(contact.AccountId);

    }

    // prevent deletion if it has associated contacts

    for (Account acc : Trigger.old) {

        if (accountIdsWithContacts.contains(acc.Id)) {

            acc.addError('This account has associated contacts and cannot be deleted.');

        }

    }

}

No comments:

Post a Comment