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
JohnDuraiJohnDurai 

Soft Delete Records using batch class

Hi All - I am Deleting the records using Btach class, but it is hard deleting it and not getting stored in Recycle bin, as part of business purpose we need this data to be stored for few days in Recycle bin, So i am trying to Soft Delete the records by making isDeleted field to true, but I am getting error that the field is not writtable, is there any alternative way to soft delete the records using apex code. Thanks! Here is my execute method code.

 global void execute(Database.BatchableContext BC , List<CampaignMember> campaignMemberScope) {
        
        system.debug('CM Records' + campaignMemberScope);
        for(CampaignMember camMemberIsDeletedTrue:campaignMemberScope){
            if(campaignMemberScope !=NULL && campaignMemberScope.size()>0){
                try{
                    //camMemberIsDeletedTrue.IsDeleted = true;
                    //Database.DeleteResult[] result =  Database.delete(campaignMemberScope, false);
                } catch(Exception e){
                    system.debug('Exception Caught:' +e.getmessage());
                }
            }
        }
    }
 
Shiraz HodaShiraz Hoda

Hi John,

The issue is that when you delete campaignmember, you are actually not deleting any data so it does not get stored in recycle bin. Contacts or leads are still there in sytem and you can recreate campaign member. Secondly, for hard delete in batch we need to use database. emptyRecycleBin() method specifically then only it will hard delete otherwise it remains in recycle bin. Please hit a like if you are satsified with answer.

JohnDuraiJohnDurai
Hi @shiraz Hoda - Thanks for your thoughts but for my case Campaignmember record is getting delted after batch run. how do i get the contacts in recycle bin?
SwethaSwetha (Salesforce Developers) 
HI John,
You might want to consider the usage of "big object" approach as mentioned in https://salesforce.stackexchange.com/questions/312652/soft-delete-in-salesforce-for-all-datafor-auditing

If this information helps, please mark the answer as best. Thank you
Shiraz HodaShiraz Hoda

Hi John,

Here is the thing, Campaign Members cannot exist without either the Campaign and the Lead or Contact (this is a many-to-many master-detail relationship). They will be cascade deleted, meaning that they will not appear in the Recycle Bin, and will be restored if the original record(s) is/are recovered from the Recycle Bin. In your case you are directly deleting campaignmembers so they will not appear in recycle bin.