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

Leave a Reply