Introduction
Trigger Lib is an Apex trigger framework for Salesforce. You write one small class per concern and give it a role in a trigger context.
Why Trigger Lib?
- One-Line Triggers - The trigger passes an orchestrator that lists each context's handlers in run order
- Record Filtering - Each handler acts only on the records its predicate picks
- Declared Queries - Declare parent fields and related records, with no SOQL in your handler
- Unit of Work - Writers register DML, committed once after the last handler by default
- Bypasses and Recursion Control - Switch handlers off in Apex or custom metadata, and cap recursion in the update contexts
- Testability - Test handlers with in-memory records, no trigger and no DML
Quick Example
trigger
trigger ContactTrigger on Contact(before insert, after insert, before update, after update, before delete, after delete, after undelete) {
TriggerOrchestrator.run(new ContactTriggerOrchestrator());
}apex
public with sharing class ContactTriggerOrchestrator implements TriggerOrchestrator.BeforeInsert {
public List<BeforeInsert.Handler> beforeInsertHandlers() {
return new List<BeforeInsert.Handler>{ new ContactEmailNormalizationPopulator() };
}
}cls
public with sharing class ContactEmailNormalizationPopulator implements BeforeInsert.Populator {
public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
return record.isNotBlank(Contact.Email);
}
public void populateOnBeforeInsert(TriggerTypes.InsertRecord record) {
Contact newContact = (Contact) record.getNewSObject();
record.put(Contact.Email, newContact.Email.trim().toLowerCase());
}
}Roles
| Role | What it does | Contexts |
|---|---|---|
| Populator | Sets fields on the record being saved. No DML. | BeforeInsert, BeforeUpdate |
| Validator | Attaches an error to the record being saved or deleted, which rejects it. | BeforeInsert, BeforeUpdate, BeforeDelete |
| Writer | Registers DML on a unit of work. | AfterInsert, AfterUpdate, BeforeDelete, AfterDelete, AfterUndelete |
| Dispatcher | Gets all qualified records at once, for async work, events or emails. | AfterInsert, AfterUpdate, AfterDelete, AfterUndelete |
