function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
THUNDER CLOUDTHUNDER CLOUD 

How to prevent Account deletion if account has open opportunity ?

Before deleting Account, check for Opportunity associated with it. If Opportunity has stage value - Closed won or Closed Lost, then only we can delete Account otherwise it will throw an error message.

How to achieve this ? 
JyothsnaJyothsna (Salesforce Developers) 
Hi,

Please check the below sample code.

Trigger:
 
trigger AccountDeletion on Account (After delete) {


for(Account a:Trigger.new){

Opportunity opp=new Opportunity();

if(a.id==opp.account.id){

if(opp.StageName=='Closed Won' || opp.StageName=='Closed Lost'){
 delete a;

}
}
else{

a.addError('You cant delete this account');
}

}
}


Kindly mark my solution as the best answer if it helps you.

Best Regards,
Jyothsna
THUNDER CLOUDTHUNDER CLOUD
Hi Jyothsna,

This will not work for multiple opportunities.


With Regards,

Thunder Cloud
Suraj Tripathi 47Suraj Tripathi 47
Hi THUNDER CLOUD,
Use this Code :
 
trigger triggerOnAccountDelete on Account (before delete) {
    list<Opportunity> opp=[select id,accountId,StageName,isClosed from opportunity where accountId in:trigger.old];
    system.debug(opp);
    for(Account a:trigger.old){
        for(Opportunity op:opp){
            if(a.id==op.accountId){
                    if(op.IsClosed==false){
                    system.debug('found');
                    a.addError('You cant delete this account because it have Some Opportunity,StageName-->'+op.StageName);
                }
            }
        }        
    }    
}


if you have any confusion plz comment.
---------------
If you find your Solution then mark this as the best answer to close this question. 

Thank you!
Regards,
Suraj Tripathi