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

Leave a Reply