Skip to content

BeforeInsert.Bypassable

Skips a handler for the whole chunk when a condition holds, such as a static flag or a batch job. To skip only some records, return false from the predicate instead.

Interface

apex
public class BeforeInsert {
    public interface Bypassable {
        Boolean bypassOnBeforeInsertWhen();
    }
}
  • bypassOnBeforeInsertWhen(): called once per chunk, before parents load; not called when metadata or TriggerOrchestrator.bypass() already skips the handler. Returns true to skip this handler for this chunk.

Example

apex
public with sharing class ContactPopulator implements BeforeInsert.Populator, BeforeInsert.Bypassable {
    public static Boolean isDisabled = false;

    public Boolean bypassOnBeforeInsertWhen() {
        return ContactPopulator.isDisabled;
    }

    public Boolean populateOnBeforeInsertWhen(TriggerHandler.InsertRecord record) {
        return record.isBlank(Contact.LeadSource);
    }

    public void populateOnBeforeInsert(TriggerHandler.InsertRecord record) {
        record.put(Contact.LeadSource, 'Web');
    }
}
cls
public with sharing class ContactReachabilityValidator implements BeforeInsert.Validator, BeforeInsert.Bypassable {
    public static Boolean isDisabled = false;

    public Boolean bypassOnBeforeInsertWhen() {
        return ContactReachabilityValidator.isDisabled || System.isBatch();
    }

    public Boolean errorShouldBeAttachedOnBeforeInsertWhen(TriggerHandler.InsertRecord record) {
        return record.isBlank(Contact.Email) && record.isBlank(Contact.Phone) && record.isBlank(Contact.MobilePhone);
    }

    public void addErrorOnBeforeInsert(TriggerHandler.RejectableInsertRecord record) {
        record.addError('A contact needs at least one way to be reached. Fill in Email, Phone or Mobile.');
    }
}

Good to Know

  • Reset static flags. A flag stays set for the rest of the transaction, nested saves included. Set it back to false in a finally block 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.
  • Inner classes need metadata or this add-on. TriggerOrchestrator.bypass().handler(X.class) never matches an inner class. Use a TriggerHandler__mdt record or Bypassable instead. See Bypassing.
  • A bypassed Validator lets records through. Records it would reject are saved.