AfterInsert.Finalizer
Run code once per chunk with the records that qualified, such as one write per parent.
Signature
apex
public interface Finalizer {
void finalizeOnAfterInsert(TriggerTypes.InsertRecords records);
}finalizeOnAfterInsert(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 AfterInsert.Writer, AfterInsert.Finalizer {
private TriggerTypes.UnitOfWork unitOfWork;
public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
return record.isNotNull(Contact.AccountId);
}
public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
this.unitOfWork = unitOfWork;
unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
}
public void finalizeOnAfterInsert(TriggerTypes.InsertRecords 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. Save the
unitOfWorkfrom the action in an instance field. - Not once per statement. A 1,000-record insert can call it 5 times.
- Registrations commit with the rest. By default after the last handler; with OwnUnitOfWork or ContinueOnError, right after the Finalizer.
WARNING
Direct DML runs at once and skips the unit of work.
