Skip to content

AfterInsert ​

Runs in after insert, after new records are saved.

Roles ​

  • Writer: change other records or publish events through a unit of work.
  • Dispatcher: make one bulk call per chunk, such as enqueueing a Queueable.

Register ​

Implement TriggerOrchestrator.AfterInsert on the orchestrator and return the handlers from afterInsertHandlers(). List order is run order. The trigger must list after insert and call TriggerOrchestrator.run(new ContactTriggerOrchestrator()).

apex
public with sharing class ContactTriggerOrchestrator implements TriggerOrchestrator.AfterInsert {
    public List<AfterInsert.Handler> afterInsertHandlers() {
        return new List<AfterInsert.Handler>{ new ContactWriter(), new ContactDispatcher() };
    }
}

Rules ​

  • Lookups hold only the Id. ((Contact) record.getNewSObject()).Account is null. Declare a ParentQuery and read record.getNewParent(Contact.AccountId).
  • Updating the new record saves it again. A Writer's toUpdate with the record Id runs before update and after update for it.
  • One role per class. A class that implements both roles runs only as a Writer.
  • Called per chunk. A 1,000-record insert is 5 runs, so each Dispatcher and Finalizer can run 5 times. Static fields keep their values across chunks.

WARNING

Rows are read-only. record.put(…) throws a System.FinalException that nothing can catch, and the insert fails. Set fields on the new record in a BeforeInsert.Populator.