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
steeeeveeeeeesteeeeveeeeee 

Undelete in an after delete trigger

Hey guys,

 

I'm running into a problem where I get the SELF_REFERENCE_FROM_TRIGGER in an after delete trigger.  My trigger is for applying additional logic for the merge operation.  Essentially when an account is deleted from a merge operation if that deleted account has a value for a field then undelete it.

 

However when I use the undelete in the after delete trigger I get something along the lines of:

SELF_REFERENCE_FROM_TRIGGER, Object (id = 001J000000RwTN2) is currently in trigger, therefore it cannot recursively undelete itself.

 

I've looked into the SELF_REFERENCE_FROM_TRIGGER erro but I can't make sense of it in this situation.  Anyone have any ideas into this?

 

Thanks

sfdcfoxsfdcfox

It appears that deletes and undeletes are in the same strata of dml events (that being "insert", "update", and "delete"), of which a record may only participate once per transaction.

 

So, it appears the correct method would be to use a @future method, which will allow them to undelete a fraction of a moment after deletion. It would look like this:

 

public class a {
  @future
  public static void recover( id[ ] records ) {
    Database.undelete( records );
  }
}

 

trigger reviveAccounts on Account ( after delete ) {
  id[ ] victims = new id[ 0 ];
  for( account record: trigger.old ) {
    if( /* should be recovered */ ) {
      victims.add( record.id );
    }
  }
  if( !victims.isEmpty( ) ) {
    a.recover( victims );
  }
}

 

Jerun JoseJerun Jose
The apex trigger execution is part of the delete transaction. Until all the triggers complete execution, the record is not yet actually deleted. So if you try to update/delete/undelete that record while it is still being processed, you will run into this issue.