BeforeInsert.Finalizer
Run code once per chunk with the records that qualified, such as a duplicate check across the new records.
Signature
apex
public interface Finalizer {
void finalizeOnBeforeInsert(TriggerTypes.InsertRecords records);
}finalizeOnBeforeInsert(records): called once per chunk, after this handler’s records, only if at least one record qualified.
Example
apex
public with sharing class ContactPopulator implements BeforeInsert.Populator, BeforeInsert.Finalizer {
public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
return record.isNotBlank(Contact.Email);
}
public void populateOnBeforeInsert(TriggerTypes.InsertRecord record) {
record.put(Contact.Email, ((Contact) record.getNewSObject()).Email.trim().toLowerCase());
}
public void finalizeOnBeforeInsert(TriggerTypes.InsertRecords records) {
Set<String> emails = new Set<String>();
for (TriggerTypes.InsertRecord record : records.getRecords()) {
Contact contactRecord = (Contact) record.getNewSObject();
if (!emails.add(contactRecord.Email)) {
contactRecord.Email.addError('Another contact in this save has the same email.');
}
}
}
}Rules
- Put it on a Populator. A Validator's qualified records already carry an error, so its Finalizer sees only rejected records.
- Reject on the row.
InsertRecordhas noaddError. Call it on a field ofrecord.getNewSObject(). - One chunk at a time. A 1,000-record insert runs in five chunks of 200. Duplicates in different chunks are never compared.
- Skipped after a swallowed exception. With ContinueOnError, an exception in the predicate or the action skips the Finalizer for that chunk.
WARNING
No DML. If the Finalizer runs DML or publishes an event, the library throws, even with ContinueOnError.
