Apex method – bulk delete

Apex method – bulk delete CodersBugs
Apex method – bulk delete

Overview

Here is the apex method which accept the List<String> with recordIds and delete all of them at once, if the record is associated with any other record then transaction will be rollback.

Code snippets

@AuraEnabled
    public static String deleteLstRecords(List <String> recordIds, String objectName) {
        try {
            Schema.DescribeSObjectResult checkObjectAccess = Schema.getGlobalDescribe().get(objectName).getDescribe();	
            if (checkObjectAccess.isDeletable()) {
                List <Id> lstRecordsToDelete = new List <Id>();
                Set <Id> deletedRecordsIds = new Set <Id>();
                for (Id  recordId: recordIds) {
                    lstRecordsToDelete.add(recordId);
                }
                Database.DeleteResult[] deleteResults = Database.delete(lstRecordsToDelete, true);
                for (Database.DeleteResult deletedId: deleteResults) {
                    if (deletedId.isSuccess())
                        deletedRecordsIds.add(deletedId.getId());
                }
            }
            return 'success';
        } catch (Exception e) {
            return 'Error deleting records: ' + e.getMessage();
        }
    }

How the code works

  1. The method receives a list of record Ids as strings and the object API name.
  2. It describes the object and checks isDeletable() to see if the user can delete it.
  3. The Ids are converted to a list of Id values.
  4. Database.delete(list, true) deletes them all. The second argument is allOrNone. When true, if any record fails, the whole transaction is rolled back and an error is thrown.
  5. The catch block returns the error message so the component can show it.

Problems to be aware of

  • If the user cannot delete the object, the method skips the delete but still returns success. It should return an error message instead.
  • The Set deletedRecordsIds is filled but never used.

Cleaner version

@AuraEnabled
public static String deleteLstRecords(List<Id> recordIds, String objectName) {
    try {
        Schema.SObjectType objType = Schema.getGlobalDescribe().get(objectName);
        if (objType == null || !objType.getDescribe().isDeletable()) {
            return 'You do not have permission to delete this object.';
        }
        Database.delete(recordIds, true);
        return 'success';
    } catch (Exception e) {
        return 'Error deleting records: ' + e.getMessage();
    }
}

FAQ

What does allOrNone do?
When true, one failed delete cancels all of them. When false, the successful records are deleted and the failures are reported in the results.

Why do some deletes fail?
Common reasons are related records that block the delete, or missing delete permission on the record.

Leave a Reply