Trigger: Prevent Account from Deleting if it has Opportunities associated to it.

Example:  Write a trigger logic to prevent Account from Deleting if it has Opportunities associated to it.

Solution

if(trigger.isBefore && trigger.isDelete) { 
    List<Opportunity> oppr = [SELECT Id , AccountId FROM Opportunity WHERE AccountId =: Trigger.old];
    if(!oppr.isEmpty() && oppr.size() > 0) { 
        for(Account newAccount : trigger.old) { 
            newAccount.addError('Connect delete as it has Opportunities');
        }
    }
}

This Post Has 2 Comments

  1. shivam

    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. shivam

    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 Reply