Restrict Record Deletion Using Salesforce Trigger : Shubham
by: Shubham
blow post content copied from SalesForce FAQs
click here to view original post
### Summary of Content The article discusses how to prevent the deletion of Salesforce records, specifically Accounts, that have active Opportunities. Salesforce does not automatically restrict this action, so developers must create a trigger to handle it. The process involves using an Apex Trigger and a Trigger Helper class to implement the business logic. Key Steps Explained: 1. **Understanding Triggers:** A Trigger is a piece of code that automatically executes before or after a specific database operation occurs. 2. **Creating a Helper Class:** This class includes methods that define the logic to restrict deletions. In this case, it checks if any Opportunities linked to an Account are still open. 3. **Implementing the Logic:** When users attempt to delete an Account, the trigger checks for active Opportunities. If any exist, it prevents deletion by displaying an error message. 4. **Trigger Execution:** The provided code snippet illustrates how to create both the helper class and the trigger, ensuring that deletion is only allowed when all associated Opportunities are closed. ### Additional Context This type of functionality is essential in Salesforce environments to maintain data integrity and ensure that important records aren’t inadvertently deleted, particularly in business contexts where active sales opportunities are tied to accounts. ### Conclusion This article effectively demonstrates how to utilize Apex triggers in Salesforce to safeguard critical records by implementing a structured approach through helper classes. This enhances the maintainability of the code and adheres to best practices in Salesforce development. ### Hashtags for SEO #Salesforce #ApexTrigger #RecordDeletion #SalesforceDevelopment #DataIntegrity #SalesforceTutorial #TriggerHelper #SalesforceBestPractices #CRM #SalesforceApex
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.

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

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.

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

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.

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.

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.

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.

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

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:
- Write a Test Class For an Apex Trigger in Salesforce
- Trigger Context Variable in Salesforce Apex
- Trigger Handler Pattern in Salesforce Apex
- CANNOT EXECUTE FLOW TRIGGER Error With DML Operation in Salesforce
- Before vs After Triggers in Salesforce: When to Use & Why
The post Restrict Record Deletion Using Salesforce Trigger appeared first on SalesForce FAQs.
September 01, 2025 at 10:46PM
Click here for more details...
=============================
The original post is available in SalesForce FAQs by Shubham
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Post a Comment