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
SzymonSzymon 

Insert records into custom object using an Apex class

Hi, wonder if anyone could guide me in the right direction. Got the below class but the requirement has changed since and now I need to insert the id's of deleted records into a custom object for tracking purposes before they get deleted. any ideas? Thanks
 
global class BatchDeletion implements Database.Batchable<sObject>, Schedulable{   
    global BatchDeletion(){}

    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator([Select id from Case where Archived__c='true']);
    } 

    //Execute method for the Schedulable interface
    global void execute(SchedulableContext sc){   
        //execute the batch
        BatchDeletion deleteCS = new BatchDeletion();
        ID batchprocessid = Database.executeBatch(deleteCS);
    }

    //Execute method for the batchable interface
    global void execute(Database.BatchableContext BC, list<sObject> scope){     
        delete scope;   
        DataBase.emptyRecycleBin(scope); 
    }

    global void finish(Database.BatchableContext BC){}
}

 
Best Answer chosen by Szymon
Om PrakashOm Prakash
Bellow modified code of your execute method will work after changing your actual api name.
Assumption : Custom Object API = CustomObject__c  and field to store the case id is DeletedCaseId__c
//Execute method for the batchable interface
    global void execute(Database.BatchableContext BC, list<sObject> scope){     
	
	    List<CustomObject__c> lstObj  = new List<CustomObject__c>();
	    for(sObject objCase : scope){
			CustomObject__c obj = new CustomObject__c();
			obj.DeletedCaseId__c = String.valueOf(objCase.get('id'));
			lstObj.add(obj);
		}
		
		insert lstObj; 
		
        delete scope;   
		
        DataBase.emptyRecycleBin(scope); 
    }

 

All Answers

Om PrakashOm Prakash
Bellow modified code of your execute method will work after changing your actual api name.
Assumption : Custom Object API = CustomObject__c  and field to store the case id is DeletedCaseId__c
//Execute method for the batchable interface
    global void execute(Database.BatchableContext BC, list<sObject> scope){     
	
	    List<CustomObject__c> lstObj  = new List<CustomObject__c>();
	    for(sObject objCase : scope){
			CustomObject__c obj = new CustomObject__c();
			obj.DeletedCaseId__c = String.valueOf(objCase.get('id'));
			lstObj.add(obj);
		}
		
		insert lstObj; 
		
        delete scope;   
		
        DataBase.emptyRecycleBin(scope); 
    }

 
This was selected as the best answer
SzymonSzymon
Thanks Prakash. Worked perfectly!