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
Rohit Vaidya 3Rohit Vaidya 3 

trigger to prevent deletion

I need to write a trigger to prevent the deletion of account records 
Arun Kumar 1141Arun Kumar 1141
Hi Rohit,
try this code below
 
trigger PreventDelete on Account (before delete) {
    if(trigger.Isbefore && trigger.IsDelete){
        for(Account ac:trigger.old){
            ac.adderror('can't delete account records');
        }
    }

}

 
Charles MurphyCharles Murphy

I bet it will look better if so:

trigger PreventDelete on Account (before delete) {
    if(Trigger.isBefore && Trigger.isDelete){
        for(Account acc : Trigger.old){
            acc.addError('Cannot delete account records');
        }
    }
}

Prateek Prasoon 25Prateek Prasoon 25
trigger PreventAccountDeletion on Account (before delete) {
  // Get the records that are being deleted
  List<Account> accountsToDelete = Trigger.old;
  
  // Loop through each account record
  for(Account acc : accountsToDelete) {
    // If the account record has any related records, prevent the deletion
    if(acc.Opportunities.size() > 0 || acc.Contacts.size() > 0) {
      acc.addError('Cannot delete account record with related records.');
    }
  }
}

If you find my answer helpful, please mark it as the best answer. Thanks!
Rohit Vaidya 3Rohit Vaidya 3
in continuation to my question , what if the account have active case and as per the rule we cannot delete the accounts having active cae and still we want to delete it how can we achive that
SubratSubrat (Salesforce Developers) 
Hello Rohit ,

If you want to delete an account with active cases, you will need to first close all the associated cases. Once the cases are closed, you can delete the account record. You can also consider writing a custom Apex method or Visualforce page to automate this process and ensure that all associated cases are closed before the account is deleted.

Try with below trigger :
trigger PreventAccountDeletion on Account (before delete) {
    // Get a list of all the accounts that are being deleted
    List<Account> accountsToDelete = Trigger.old;
    
    // Create a set to hold the IDs of all the accounts that have active cases
    Set<Id> accountsWithActiveCases = new Set<Id>();
    
    // Query for all the accounts that have active cases
    for (Case c : [SELECT AccountId FROM Case WHERE AccountId IN :accountsToDelete AND Status != 'Closed']) {
        accountsWithActiveCases.add(c.AccountId);
    }
    
    // If any of the accounts being deleted have active cases, prevent the deletion
    for (Account a : accountsToDelete) {
        if (accountsWithActiveCases.contains(a.Id)) {
            a.addError('You cannot delete this account because it has active cases.');
        }
    }
}

If it helps , please mark this as Best Answer.
Thank you.