AfterInsert.Writer
Change other records or publish platform events after the insert, through a unit of work.
Signature
apex
public interface Writer extends AfterInsert.Handler {
Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record);
void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork);
}writeOnAfterInsertWhen(record): called once per record in the chunk. Returntrueto write for the record.writeOnAfterInsert(record, unitOfWork): called right after its predicate returns true, with this Writer’s unit of work.
Example
apex
public with sharing class ContactWriter implements AfterInsert.Writer {
public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
return record.isNotNull(Contact.AccountId);
}
public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
}
}cls
public with sharing class AccountWelcomeTaskWriter implements AfterInsert.Writer, AfterInsert.ParentQuery, AfterInsert.ContinueOnError {
public Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnAfterInsert() {
return new Map<SObjectField, TriggerTypes.ParentFields>{ Account.OwnerId => TriggerTypes.ParentFields.with(User.Name, User.Email) };
}
public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
return record.startsWith(Account.Type, 'Customer');
}
public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
Account newAccount = (Account) record.getNewSObject();
User owner = (User) record.getNewParent(Account.OwnerId);
unitOfWork.toInsert(
new Task(
WhatId = record.getId(),
OwnerId = newAccount.OwnerId,
Subject = 'Onboarding call - ' + newAccount.Name,
Description = 'New customer assigned to ' + owner?.Name + ' (' + owner?.Email + '). Confirm the billing address and the primary contact.',
ActivityDate = Date.today().addDays(3),
Priority = 'High',
Status = 'Not Started'
)
);
}
}cls
public with sharing class ContactOwnerAlignmentWriter implements AfterInsert.Writer, AfterInsert.ParentQuery, AfterInsert.Bypassable {
public static Boolean isBypassed = false;
public Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnAfterInsert() {
return new Map<SObjectField, TriggerTypes.ParentFields>{ Contact.AccountId => TriggerTypes.ParentFields.with(Account.OwnerId).with('Owner', User.IsActive) };
}
public Boolean bypassOnAfterInsertWhen() {
return ContactOwnerAlignmentWriter.isBypassed;
}
public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
Contact newContact = (Contact) record.getNewSObject();
Account account = (Account) record.getNewParent(Contact.AccountId);
return account?.Owner?.IsActive == true && account.OwnerId != newContact.OwnerId;
}
public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
Account account = (Account) record.getNewParent(Contact.AccountId);
unitOfWork.toUpdate(new Contact(Id = record.getId(), OwnerId = account.OwnerId));
}
}Rules
- Register, don't run DML. Call
toInsert,toUpdate,toUpsert,toDeleteortoPublish(platform events) onunitOfWork. DML in the predicate or the action throws. - By default, later handlers don't see your writes. The shared unit of work commits after the last handler. With OwnUnitOfWork or ContinueOnError, it commits right after this Writer.
- Inserting the same object runs after insert again. Insert contexts have no RecursionGuard. Only your predicate stops the chain.
- Writer wins. A class that also implements
AfterInsert.Dispatcherruns only as a Writer.
WARNING
The row is read-only. record.put(…) throws, and the insert fails. To change the new record, register toUpdate(new Contact(Id = record.getId(), …)), which saves it again and runs the update triggers.
Test
apex
@IsTest
static void writeOnAfterInsertWithCustomer() {
// Setup
Account acme = new Account(Name = 'Acme', Type = 'Customer - Direct');
DML.mock('triggerUow').allDmls();
TriggerOrchestrator.mock().afterInsertFor(AccountWelcomeTaskWriter.class).with(acme);
// Test
TriggerOrchestrator.runTestFor(new AccountWelcomeTaskWriter());
// Verify
Assert.areEqual('Onboarding call - Acme', ((Task) DML.retrieveResultFor('triggerUow').insertsOf(Task.SObjectType).records()[0]).Subject, 'The task subject should name the account.');
}