Skip to content

BeforeDelete.Finalizer ​

Run code once per chunk with the records that qualified, such as one registration per parent.

Signature

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

Example

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

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

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

    public void finalizeOnBeforeDelete(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 writeOnBeforeDelete, as the Skeleton does. Its writes commit with the rest.
  • The rows still exist. A query by records.getIds() still finds the records being deleted and the records that point at them.
  • An exception skips it. When the action throws, the Finalizer does not run for that chunk.

WARNING

Leave the records being deleted alone. A toDelete of one fails the commit with SELF_REFERENCE_FROM_TRIGGER, and an update of one is lost when the delete goes through.