0

I have a custom object in salesforce called : File_Uploaded__c with many fields such as Name, Size, DeletionDate__c and i declared a trigger to set the deletion date when a record is deleted, here's my trigger code:

trigger setDeletionDate on File_Uploaded__c (before delete) {
    for (File_Uploaded__c f: Trigger.old) {
       f.DeletionDate__c = date.Today();
    }
}

But when i try to delete a record of my custom object i get this error:

There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger setDeletionDate caused an unexpected exception, contact your administrator: setDeletionDate: execution of BeforeDelete caused by: System.FinalException: Record is read-only: Trigger.setDeletionDate: line 3, column 1". 

EDIT 1:

I changed Trigger.old to Trigger.new I'm getting a new error:

 There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger setDeletionDate caused an unexpected exception, contact your administrator: setDeletionDate: execution of BeforeDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.setDeletionDate: line 2, column 1". 
3
  • You can't modify records in the trigger set during a before delete trigger - the record will be deleted and hence updating it doesn't make sense since you won't be seeing it again in a query
    – cropredy
    May 22, 2015 at 9:19
  • so how can i update DeletionDate__c field when i delete my object ?
    – ihssan
    May 22, 2015 at 9:21
  • i'm not 100% sure but systemModstamp may have the deleted date. Others on SFSE can confirm this
    – cropredy
    May 22, 2015 at 9:29

1 Answer 1

0

after searching and trying many solutions, i finally find one, i let the code here if any one has the same problem:

trigger setDeletionDate on File_Uploaded__c (before delete) {
Set<Id> fileIds = Trigger.oldMap.keyset();
list<File_Uploaded__c> files = [SELECT Id, DeletionDate__c FROM File_Uploaded__c WHERE Id IN :fileIds];  
for (File_Uploaded__c f: files) {
       f.DeletionDate__c = system.now();
       update f;
 } 
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .