BeforeInsert.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 bypassOnBeforeInsertWhen();
}bypassOnBeforeInsertWhen(): called once per chunk, before parents load. Returnstrueto skip this handler for this chunk.
Example
apex
public with sharing class ContactPopulator implements BeforeInsert.Populator, BeforeInsert.Bypassable {
public static Boolean isBypassed = false;
public Boolean bypassOnBeforeInsertWhen() {
return ContactPopulator.isBypassed;
}
public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
return record.isBlank(Contact.LeadSource);
}
public void populateOnBeforeInsert(TriggerTypes.InsertRecord record) {
record.put(Contact.LeadSource, 'Web');
}
}cls
public with sharing class ContactReachabilityValidator implements BeforeInsert.Validator, BeforeInsert.Bypassable {
public static Boolean isBypassed = false;
public Boolean bypassOnBeforeInsertWhen() {
return ContactReachabilityValidator.isBypassed || System.isBatch();
}
public Boolean addErrorOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
return record.isBlank(Contact.Email) && record.isBlank(Contact.Phone) && record.isBlank(Contact.MobilePhone);
}
public void addErrorOnBeforeInsert(TriggerTypes.RejectableInsertRecord record) {
record.addError('A contact needs at least one way to be reached. Fill in Email, Phone or Mobile.');
}
}Rules
- Reset static flags. A flag stays set for the rest of the transaction, nested saves included. Set it back to false in a
finallyblock after your DML. - Checked before any handler runs. A flag that an earlier handler sets takes effect only from the next chunk.
- Exceptions here are not logged. The method runs outside the handler's error handling. An exception fails the insert, even with ContinueOnError.
- 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.
TIP
To skip only some records, return false from the predicate instead.
