Please refer the below code :
Explanation : Here My_Demo_ChkBx__c is ur check box which is getting updated once 30 days has passed. The query is getting the attachments related to case object that has being closed 30 earlier.
trigger DeleteAttmt_After30DClose on Case (Before Update,After Update) {
public Set<Id> CaseSetId = new Set<Id>();
List<Case> csToUpdt = new List<Case>();
//Section used to update the description as 'Attachment is deleted'
if(Trigger.isBefore && Trigger.isUpdate){
for(Case cs:Trigger.New){
if(cs.My_Demo_ChkBx__c== True){
cs.Description = 'Attachment is deleted';
}
}
}
if(Trigger.isAfter && Trigger.isUpdate){
for(Case cs:Trigger.New){
if(cs.My_Demo_ChkBx__c== True){
CaseSetId.add(cs.Id);
}
}
If(CaseSetId.size()>0){
List<Attachment> casAttmtList = [SELECT Id,ParentId FROM Attachment WHERE ParentId in: CaseSetId];
delete casAttmtList;
List<CaseComment> childCommand = new List<CaseComment>();// Forming case comment list.
for(Id cseID:CaseSetId){
CaseComment newCommmand = new CaseComment();
newCommmand.CommentBody = 'Attachment is deleted';
newCommmand.IsPublished = TRUE;
newCommmand.ParentId = cseID;
childCommand.add(newCommmand);
}
if(!childCommand.isEmpty()){
insert childCommand;
}
}
}
}
WE also need to write the scheduler class . This scheduler class will help to check the checkbox "My_Demo_ChkBx__c" to true once the desired day (here 30 days) has passed after the case is Closed. Once the check box is checked the Trigger will do its task : deleting the attachment and do case comment.
Schdeuler Class:
global class CaseClsAge_Scheduled Implements Schedulable{
global void execute(SchedulableContext sc){
chkCLoseAge();
}
public void chkCLoseAge(){
List<Case> listCases = new List<Case>();
listCases = [SELECT ID,My_Demo_ChkBx__c,ClosedDate FROM Case WHERE Status = 'Closed' and My_Demo_ChkBx__c = False];
List<Case> lstCaseToUpadte = new List<Case>();
for(Case cc : listCases)
{
integer intDays = cc.ClosedDate.Date().daysBetween(system.now().Date());
if(intDays > 1){
cc.My_Demo_ChkBx__c = True;
lstCaseToUpadte.add(cc);
}
}
if(lstCaseToUpadte.size()>0){
update lstCaseToUpadte;
}
}
}
PS: This need to be schedule afterwards you can go to Setup > Build > Develop > Apex Classes and then press on the 'Schedule Apex' to set up your class.