AfterInsert.Bypassable
Skip a handler for the whole chunk when a condition holds, such as a static flag, a batch job or a custom permission.
Signature
apex
public interface Bypassable {
Boolean bypassOnAfterInsertWhen();
}bypassOnAfterInsertWhen(): called once per chunk, before parents load. Returnstrueto skip this handler for this chunk.
Example
apex
public with sharing class ContactWriter implements AfterInsert.Writer, AfterInsert.Bypassable {
public static Boolean isBypassed = false;
public Boolean bypassOnAfterInsertWhen() {
return ContactWriter.isBypassed;
}
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 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
- To skip single records, return false from the predicate.
- Checked before the first handler runs. A flag that an earlier handler sets takes effect from the next chunk.
- Static flags last the transaction.
ContactOwnerAlignmentWriter.isBypassed = truestays set for every later chunk and nested save until you reset it. - Only this context. Apex bypasses cover every context, and
bypass().handler(X.class)never matches an inner class. ATriggerHandler__mdtrecord covers the one context it names, for every user.
WARNING
An exception from bypassOnAfterInsertWhen() is not logged, ContinueOnError does not apply, and the insert fails.
