Sometimes, there arises a need to delete records from an object in Salesforce. To address this requirement efficiently, we can utilize a batch class that handles the deletion process. This solution leverages the power of custom metadata types to pass the object information, offering flexibility and easy maintenance. By modifying the custom metadata records, instead of modifying the batch class itself, you can effortlessly manage the deletion process.
In this blog post, we will explore an approach that enables you to delete records in a more dynamic and scalable manner, reducing manual effort and providing a robust solution for record deletion.
Batch Class:-
Global class DeleteRecords Implements Database.batchable<sobject>,database.stateful {
global string query;
global integer totalSizeRecords=0;
global Database.QueryLocator start(Database.BatchableContext BC){
Delete_Records_Setting__mdt delObj = Delete_Records_Setting__mdt.getInstance('Delete_Records_Setting');
if(delObj.Is_Active__c==true){
//createed date format
Datetime Dt = datetime.newInstance(delObj.Created_Date__c.year(), delObj.Created_Date__c.month(),delObj.Created_Date__c.day());
String startDate = Dt.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
//end date format
Datetime EndDt = datetime.newInstance(delObj.End_Date__c.year(), delObj.End_Date__c.month(),delObj.End_Date__c.day());
String EndDate = EndDt.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
query='SELECT Id, CreatedDate FROM '+delObj.Object_Name__c+' where CreatedDate>='+startDate+' and CreatedDate<='+EndDate;
}
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,List<SObject> scope){
try{
Database.DeleteResult[] drList = Database.delete(scope, false);
for(Database.DeleteResult dr : drList) {
if (dr.isSuccess()) {
System.debug('Successfully deleted records with ID: ' + dr.getId());
}else {
for(Database.Error err : dr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Fields that affected this error: ' + err.getFields());
}
}
}
}catch(exception ex){
System.debug('Exception is here '+ex);
}
}
global void finish(Database.BatchableContext BC){
}
}
Custom Metadata: