Skip to content

AfterDelete.Finalizer ​

Run code once per chunk with the records that qualified, such as one aggregate query or one write per former parent.

Signature

apex
public interface Finalizer {
    void finalizeOnAfterDelete(TriggerTypes.DeleteRecords records);
}
  • finalizeOnAfterDelete(records): called once per chunk, after this handler’s records, only if at least one record qualified; after the dispatch for a Dispatcher.

Example

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

    public Boolean writeOnAfterDeleteWhen(TriggerTypes.DeleteRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterDelete(TriggerTypes.DeleteRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        this.unitOfWork = unitOfWork;
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getOldSObject()).AccountId, Subject = 'Review contact'));
    }

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

Rules ​

  • Keep the unit in a field. The Finalizer gets no unit of work. Store the one from writeOnAfterDelete, as the Skeleton does. Its writes commit with the rest.
  • Aggregate over what remains. The deleted rows are gone from SOQL, so a query over the former parents' children counts only the survivors.
  • A swallowed throw skips the commit, not the dispatch. With ContinueOnError, a Writer's automatic unit commits after the Finalizer, so its writes are lost. A Dispatcher's call already ran.

INFO

Not an end-of-statement hook. It runs at this handler's turn, before later handlers and before the unit of work commits.