Restrict Record Deletion Using Salesforce Trigger

While working as a Salesforce developer, I was required to write a trigger to restrict record deletion, as sometimes we need to prevent users from deleting important records.

For example, An Account should not be deleted if it has active Opportunities. Salesforce does not provide this restriction by default, so we need a trigger to delete the records.

In this article, I will explain how to restrict record deletion using a Salesforce Trigger. In this, I will explain the trigger helper and handler class for best practices.

Restrict Record Deletion Using Salesforce Trigger

Now, let’s understand how to write a trigger helper and a handler class to prevent users from deleting important records.

For example, we want to prevent the deletion of those accounts that still have active opportunities. That means a user will only be able to delete an account if all its opportunities are already closed (either Won or Lost).

In simple words, if there is at least one open opportunity related to an account, Salesforce will prevent the deletion to protect an important record.

Create Trigger Helper Class in Salesforce

A trigger helper class is simply an Apex class where we create different methods and implement the business logic required to achieve our desired outcome. Instead of writing all the logic directly inside the trigger, we keep it in the helper class.

First, we will create a helper class to implement the logic that prevents the deletion of accounts with active opportunities (excluding those marked as Closed Won or Closed Lost).

To create the class, go to Setup Developer Console -> File -> New -> Apex Classes → and then write the Apex class with the required logic.

Create Apex Trigger Helper and Handler Class in Salesforce

Below, I have developed a helper class where I implemented the logic as follows:

  • Collect Account IDs: From the records that users are trying to delete, which will be stored in a set collection.
  • Run SOQL Query: To check if any of those accounts have active opportunities (Status not Closed Won/Lost).
  • Use addError(): We used the addError() method to prevent deletion and show a clear error message to the user if active opportunities are found.
public class AccountTriggerHandler {

    public static void preventAccountDeletion(List<Account> oldAccounts) {
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : oldAccounts) {
            accountIds.add(acc.Id);
        }

        Map<Id, Integer> accountOppCount = new Map<Id, Integer>();
        for (AggregateResult ar : [
                                                                    SELECT AccountId, COUNT(Id) totalOpps
                                                                    FROM Opportunity
                                                                   WHERE AccountId IN :accountIds
                                                                   AND IsClosed = false
                                                                  GROUP BY AccountId
                                                                 ])
            {
            accountOppCount.put((Id)ar.get('AccountId'), (Integer)ar.get('totalOpps'));
        }

        for (Account acc : oldAccounts) {
            if (accountOppCount.containsKey(acc.Id) && accountOppCount.get(acc.Id) > 0) {
                acc.addError('You cannot delete this Account because it has active Opportunities.');
            }
        }
    }
}
Salesforce Trigger Helper Class

After creating the helper class, we ned to call its methods in the handler (trigger) class to execute on the delete operation.

Create Trigger Class in Salesforce

This class includes methods for various trigger events, such as ‘before insert’ and ‘after update’, and processes the logic relevant to each event. Then the trigger class calls the helper class methods when an Account is being deleted.

Now, let’s similarly create an Apex Trigger as we created the Apex Class. This time, we need to provide the Trigger Name and select the Object (Account in our case).

Then, enter the Name of your trigger, select the Object on which you want to create the trigger from the drop-down menu of sObject, and click the Submit button.

Create New Apex Trigger in Salesforce

Then, you will see that the trigger will be created according to the name and sObject you provided. With that, you will also see a default trigger event displayed. You can change the trigger event according to your requirements.

Here, I added an if condition to check whether, using the context variable, we are calling events, which are isBefore and isDelete. Then, using the helper class name, call the methods in the order you want to execute.

trigger RestrictAccountDeletion on Account (before delete) {
    
     if (Trigger.isBefore && Trigger.isDelete) {
        AccountTriggerHandler.preventAccountDeletion(Trigger.old);
    }
}
Salesforce Trigger Handler Class

Proof of Concept

Now, navigate to the Apex Triggers from Setup. For that, search for the Apex Trigger in the Quick Find box, and there you will see the trigger Name and Status

If the status is Active, then it will work. Otherwise, the trigger will not automate the process of preventing the deletion of an account with active opportunities.

Check Apex Triggers Status in Salesforce Lightning

I have now opened an account that has two related opportunities: one is already closed, while the other is still active in the Prospecting stage.

When I click on the Delete button for this account, the trigger executes, checks for active opportunities, and immediately prevents the deletion.

Prevent Account From Deletion using Apex Trigger in Salesforce

Instead of allowing the record to be removed, Salesforce displays an error message on the screen, informing the user that this Account cannot be deleted because it still has active Opportunities.

Restrict Record Deletion Using Salesforce Trigger

Now, I opened another Account that has only one related Opportunity, and this Opportunity is already in a Closed stage. When I click on the Delete button for this Account, the trigger runs, checks for active Opportunities, and finds none.

Use Apex Trigger in Salesforce

Since there are no active Opportunities, Salesforce allows the deletion to proceed successfully, and the Account record is removed without showing any error message.

Use Apex Trigger Handler class in Salesforce

Conclsuion

I hope you have got an idea about how we can use an Apex Trigger along with a Helper Class to restrict the deletion of Accounts that still have Active Opportunities, and only allow deletion when all Opportunities are closed.

I also showed a proof of concept where I tried to delete an Account with an Active Opportunity, and Salesforce displayed an error message preventing the deletion. Then, when I deleted an Account that only had Closed Opportunities, the deletion was successful without any errors.

You may like to read:

live webinar

Data Cloud in Agentforce Data Library

In this live webinar, we will showcase how Salesforce AI Agents use business data and documents to provide intelligent responses using Agentforce Data Library and Salesforce Data Cloud.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.