2 thoughts on “Trigger: Prevent Account from Deleting if it has Opportunities associated to it.”

  1. trigger getAccountRelatedOpportunity on Account (before delete) {
    Set accountIdsToDelete = new Set();

    if (Trigger.isBefore && Trigger.isDelete) {
    for (Account acc : Trigger.old) {
    accountIdsToDelete.add(acc.Id);
    }

    // Query all Opportunities linked to the Accounts being deleted
    Set accountsWithOpportunities = new Set();
    for (Opportunity opp : [SELECT Id, AccountId FROM Opportunity WHERE AccountId IN :accountIdsToDelete]) {
    accountsWithOpportunities.add(opp.AccountId);
    }

    // Add error on Accounts that have related Opportunities
    for (Account acc : Trigger.old) {
    if (accountsWithOpportunities.contains(acc.Id)) {
    acc.addError(‘Cannot delete Account because related Opportunities exist.’);
    }
    }
    }
    }

  2. trigger getAccountRelatedOpportunity on Account (before delete) {
    Set accountIdsToDelete = new Set();

    if (Trigger.isBefore && Trigger.isDelete) {
    for (Account acc : Trigger.old) {
    accountIdsToDelete.add(acc.Id);
    }

    // Query all Opportunities linked to the Accounts being deleted
    Set accountsWithOpportunities = new Set();
    for (Opportunity opp : [SELECT Id, AccountId FROM Opportunity WHERE AccountId IN :accountIdsToDelete]) {
    accountsWithOpportunities.add(opp.AccountId);
    }

    // Add error on Accounts that have related Opportunities
    for (Account acc : Trigger.old) {
    if (accountsWithOpportunities.contains(acc.Id)) {
    acc.addError(‘Cannot delete Account because related Opportunities exist.’);
    }
    }
    }
    }

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top