Skip to content

AfterUndelete.Writer ​

Change other records or publish platform events after the restore, through a unit of work.

Signature

apex
public interface Writer extends AfterUndelete.Handler {
    Boolean writeOnAfterUndeleteWhen(TriggerTypes.UndeleteRecord record);
    void writeOnAfterUndelete(TriggerTypes.UndeleteRecord record, TriggerTypes.UnitOfWork unitOfWork);
}
  • writeOnAfterUndeleteWhen(record): called once per record in the chunk. Return true to write for the record.
  • writeOnAfterUndelete(record, unitOfWork): called right after its predicate returns true, with this Writer’s unit of work.

Example

apex
public with sharing class ContactWriter implements AfterUndelete.Writer {
    public Boolean writeOnAfterUndeleteWhen(TriggerTypes.UndeleteRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterUndelete(TriggerTypes.UndeleteRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }
}
apex
public with sharing class AccountRestoreGuardWriter implements AfterUndelete.Writer {
    public Boolean writeOnAfterUndeleteWhen(TriggerTypes.UndeleteRecord record) {
        return !FeatureManagement.checkPermission('Restore_Accounts');
    }

    public void writeOnAfterUndelete(TriggerTypes.UndeleteRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        record.getNewSObject().addError('You are not allowed to restore accounts.');
    }
}

Rules ​

  • Register, don't run DML. Call toInsert, toUpdate, toUpsert, toDelete or toPublish (platform events) on unitOfWork. DML in the predicate or the action throws.
  • A self-update is a second save. unitOfWork.toUpdate(new Account(Id = record.getId(), …)) fires BeforeUpdate and AfterUpdate for the restored record.
  • Block a restore with addError. There is no Validator here. List the blocking Writer first. The record stays in the Recycle Bin.
  • Writer wins. A class that also implements AfterUndelete.Dispatcher runs only as a Writer.

WARNING

A self-delete fails. A toDelete of a record being restored throws a DmlException with SELF_REFERENCE_FROM_TRIGGER.

Test ​

apex
@IsTest
static void writeOnAfterUndeleteWithoutPermission() {
    // Setup
    Account acme = new Account(Name = 'Acme');

    TriggerOrchestrator.mock().afterUndeleteFor(AccountRestoreGuardWriter.class).with(acme);

    // Test
    TriggerOrchestrator.runTestFor(new AccountRestoreGuardWriter());

    // Verify
    Assert.areEqual('You are not allowed to restore accounts.', acme.getErrors()[0].getMessage(), 'The restore should be rejected.');
}