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
Pankaj Yadav 29Pankaj Yadav 29 

how to prevent delete of account related to opportunity when opportunity

trigger OpportunityOpen on Account(before delete)
{
        Set<Id> setacc = new Set<Id>();
        for(Account a : trigger.old)
        {
            setacc.add(a.Id);
        }

        List<Account> acclist = [Select Id, Name,
        (Select AccountId, Name, StageName From Opportunities)From Account Where Id In :setacc];
        for(Account a : acclist)
        {
            for(Opportunity opp : acclist.Opportunities)
            {
                if(opp.StageName=='closedwon')
                {
                    a.addError('you should not delete the account because a closedwon opportunity');
                }
            }
        }
}

 
Anshul Bansal 23Anshul Bansal 23

Please  use the  below Code :-

trigger OpportunityOpen on Account(before delete) {
    Set<Id> setacc = new Set<Id>();
    for(Account a : trigger.old) {
         setacc.add(a.Id);
     }
    List<Account> acclist = [Select Id, Name, (Select AccountId, Name, StageName From Opportunities)From Account Where Id In :setacc];                  for(Account a : acclist) {
         for(Opportunity opp : a.Opportunities) {
              if(opp.StageName=='Closed Won') {
                  a.addError('you should not delete the account because a closedwon opportunity');
              }
         }
     }
}

if this solution is helpful for you. then Mark as Best Answer.