Skip to content

AfterUndelete.Finalizer

Runs once per chunk after a Writer or Dispatcher, with the restored records that qualified. Use it for one aggregate query or one bulk registration instead of one per record.

Interface

apex
public class AfterUndelete {
    public interface Finalizer {
        void finalizeAfterUndelete(TriggerHandler.UndeleteRecords records);
    }
}
  • finalizeAfterUndelete(records): called once per chunk, after this handler’s records, only if at least one record qualified; after the dispatch for a Dispatcher. It receives only the qualified records.

Example

apex
public with sharing class ContactWriter implements AfterUndelete.Writer, AfterUndelete.Finalizer {
    private TriggerHandler.UnitOfWork unitOfWork;

    public Boolean writeOnAfterUndeleteWhen(TriggerHandler.UndeleteRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterUndelete(TriggerHandler.UndeleteRecord record, TriggerHandler.UnitOfWork unitOfWork) {
        this.unitOfWork = unitOfWork;
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }

    public void finalizeAfterUndelete(TriggerHandler.UndeleteRecords records) {
        for (Id accountId : records.getIdsOf(Contact.AccountId)) {
            this.unitOfWork.toUpdate(new Account(Id = accountId, Description = 'Contacts changed'));
        }
    }
}

Good to Know

  • Keep the unit of work in a field. The Finalizer receives only the records. Store the unitOfWork from the action, as the Skeleton does. What you register here commits with the Writer's other writes.
  • Once per chunk. Restoring 1,000 records runs it 5 times. It is not an end-of-restore hook.
  • Don't clear records.getRecords(). It is the library's own list, not a copy. Clearing it makes a Writer with OwnUnitOfWork or ContinueOnError skip its commit.
  • Direct DML runs at once. It is not merged with any unit of work.