Trigger to permanently delete records salesforce

Trigger to permanently delete records
Trigger to permanently delete record in salesforce apex

Once we delete any record from salesforce object that record get stored in salesforce recycle bin for next 15 days. If you want to permanently delete that record you have to delete it from recycle bin. There are some ways to prevent this case such as you can hard delete record using hard delete option.

You can locate to the recycle bin in salesforce classic by – https://your-org/search/UndeletePage

In this blog you will learn how to write trigger to automatically delete record from recycle bin. 

Trigger to automatically delete records from recycle bin

				
					trigger DeleteRecFromRecycleBin on Account (after delete) {
    for(Account deletedAcc : Trigger.old) {
        Database.emptyRecycleBin(Trigger.old);
    }   
}
				
			

Here we have written trigger on Account which will get executed after deleting one or more records.

Here we are using emptyRecycleBin method which can take sObject or List<sObjects> as an argument.

How the trigger works

The trigger runs after delete on Account. The deleted records are in Trigger.old, and Database.emptyRecycleBin removes them from the Recycle Bin so they cannot be restored.

Problem in this version

The call sits inside a for loop, but it passes the whole list each time. With 50 deleted Accounts, the same call runs 50 times. The loop is not needed. One call with the full list does the job.

Improved trigger

trigger DeleteRecFromRecycleBin on Account (after delete) {
    Database.emptyRecycleBin(Trigger.old);
}

Important warnings

  • This cannot be undone. Once a record is removed from the Recycle Bin you cannot restore it. Use it only where you are sure about the business need.
  • Records deleted together with an Account, such as its Contacts, are not part of Trigger.old, so they stay in the Recycle Bin.
  • The user who deletes the record needs permission to empty the Recycle Bin for it.
  • Test in a sandbox first.

Other ways to hard delete

You can also delete records permanently from Apex with Database.emptyRecycleBin(records) after a normal delete, or use the Hard Delete option in Data Loader (it needs the Bulk API Hard Delete permission).

FAQ

How long do deleted records stay in the Recycle Bin?
15 days, unless the bin is full.

Does it accept a single record?
Yes. emptyRecycleBin accepts a single sObject, a list of sObjects, or a list of Ids.

Leave a Reply