Block Account Deletion with Related Opportunities

This trigger prevents deletion of an Account if it has any related Opportunities, ensuring no critical relationships are accidentally removed.

Practice similar use cases with this YouTube playlist.

Solution:

trigger AccountTrigger on Account (before delete) {
          if(Trigger.isDelete){ if(Trigger.isBefore){
                                                              AccountTriggerHandler.preventDelIfHasRelatedOpp(Trigger.old);
                       }
          }
}
public class AccountTriggerHandler{
     public static void preventDelIfHasRelatedOpp(List<Account> accList){ Set<Id>
     idSet= new Set<Id>();
     for(Account acc:accList){ idSet.add(acc.Id);
      }
      for(Account acc:[SELECT Id,(SELECT Id FROM Opportunities)FROM
                  Account WHERE Id IN:idSet]){ if(acc.Opportunities.size( ) > 0){ acc.addError(‘You can
                      not delete account where opportunities are available ‘); }
      }
  }
}

Want to Apply As Content Writer?

Leave a Comment

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

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)