I need to delete some events and after undelete them. Now to do this i'm using two triggers, the first in after insert delete all the events if they are alldayevent,the second trigger undelet a list of events under certain conditions.

the second trigger is:

trigger eventundeleter on Event (after delete) {
List<Event> eventi=[select Id,Subject,Priorit_Alta__c,IsAllDayEvent,Whoid,ShowAs,ordinatozz__c,Description,WhatId,Location,
                   from Event
                   where  Undeleting__c=true  AND IsAllDayEvent=true
                   ORDER BY ordinatozz__c,StartDateTime ASC ALL ROWS];
System.debug('list to be undeleted: '+ eventi);
undelete eventi; 

Salesforce give me this error, but I don't understand why:

eventundeleter: execution of AfterDelete caused by: System.DmlException: Undelete failed. First exception on row 4 with id 00U58000003EfE5EAK; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 00U58000003EfE5) is currently in trigger eventundeleter, therefore it cannot recursively undelete itself: [] Trigger.eventundeleter: line 11, column 1: []: Trigger.eventdeleter: line 67, column 1

how can I fix it?

  • you can create future/queueable job to do it in different context
    – kurunve
    Aug 2, 2016 at 9:33
  • I did it , but now I have another requirement, I need to undelete the records following a precise sequence. Is it possible in salesforce?. I explain better. The records have a number field "ordinato__c" and I have to recreate them from the Recycle Bin following an ordinato__c ascendent sequence. Aug 2, 2016 at 10:52
  • Hi, can you post this new part as a new question? SFSE doesn't really support major changes to the question, it doesn't work like a discussion based forum.
    – Matt Lacey
    Aug 2, 2016 at 23:37
  • I solved the problem, I used the code below Aug 3, 2016 at 14:05

1 Answer 1

  • You can definitely use a @future method for this.
  • Your parameter will be a Set<Id> to specify which records need to be restored.
  • When you re-query for the records, you can use an ORDER BY clause to specify which field to sort by (ordinato__c).
  • You can make sure your query includes records in the Recycle Bin by adding the ALL ROWS clause.

So something like:

public static void undeleteRecords(Set<Id> deletedIds)
    undelete [
        SELECT Id FROM MyObject
        WHERE Id IN :deletedIds
        ORDER BY Ordinato__c
        ALL ROWS

You must log in to answer this question.

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