Trigger Handlers
Step-by-step guide on how to set up and interact with Trigger Handlers, maximise the functions and benefits, while being aware of edge cases and D'fflib specific functionalities.
New framework upcoming
We are finalising a redesign for the D'fflib trigger handler framework . Keeping the Handler structure, but moving registration to metadata, to allow a more flexible configuration, like (partial or temporary) disablement.
Domain documentation
This article has the single responsibility to elaborate on the trigger handlers registration and implementation.
→ Click here to visit the Domain documentation, to learn how those can be initiated and used.
Characteristics
A Trigger Handler is a lean class, responsible for a specific process to happen upon a record-triggered event for a specific SObject. It can contain small business logic, or delegate to the appropriate Domain, Selector or Service method.
Responsibilities
Interactions
| Interaction | Layers |
|---|---|
| Called by | dfflib_SObjectDomain (the trigger framework) |
| Calling | Domain (of same SObject), Selectors, Services, Unit of Work (only for deviating sharing modes) |
The D'fflib Trigger Handler framework orchestrates the transactions and therefore injects a Unit of Work into a BaseHandler-implemented class.
Handlers should, thus, only register, and not initiate nor commitWork, unless one Trigger Handler needs to bypass the dfflib_Database.Context (→ see Handler-specific Context).
Rules
- Only one Trigger should exist per SObject, delegating to the Trigger Handlers.
- The Trigger only initiates the Trigger Framework, and optionally references project-specific bypassing/evaluation logic. Thus zero business logic.
- Handlers should have a clear single responsibility.
- Handlers' name should clearly describe the action it performs, e.g.,
ValidateDeactivation. Avoid generic names likeHandler1orAfterInsertHandler. - Handlers should be robust and satisfy the open-close principle.
- Handlers should be bulkified to be scalable and reusable.
- Handlers should consciously handle Exceptions, to properly log and not disrupt the overall trigger execution flow too much.
- Handlers should leverage
TriggerStateand not directly useTrigger.neworTrigger.oldto access record data, as those can't be mocked in unit tests. - Queries and DMLs should be restricted to
initialize()andfinalize(), sinceprocess()is called for each record.
fflib-apex-common has no handler classes. A Domain overrides lifecycle hooks (onBeforeInsert(), onValidate(), etc.) and either holds the logic itself or delegates from there.
The rules above apply unchanged to such hook implementations: one Trigger per SObject, zero business logic in the Trigger, bulkified, and no queries or DML inside record loops.
Both styles can live in the same Domain, so existing hook-based Domains keep working when adopting D'fflib.
Initiation
How to call
Trigger
Triggers are automatically invoked by Salesforce upon DML events on the associated SObject.
The trigger file delegates to the Trigger Handler Framework in the Domain, which runs the handlers registered for the fired event.
trigger RoomTrigger on Room__c ( before insert, before update, before delete, after insert, after update, after delete, after undelete ) {
dfflib_SObjectDomain.triggerHandler( DOM_Rooms.class );
}Domain: handler registration
In its constructor, a Domain class registers which handler responds to which event,
with one registerHandler line per event-handler pair. One handler can be registered for multiple events.
public DOM_RoomReservations( List<RoomReservation__c> sObjectList ){
super( sObjectList, dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ) );
// Register handlers
registerHandler( TriggerEvent.BEFORE_INSERT, CalculateTotalPrice.class );
registerHandler( TriggerEvent.BEFORE_UPDATE, CalculateTotalPrice.class );
}The Trigger file is nearly identical: fflib_SObjectDomain.triggerHandler( DOM_Rooms.class ). The Domain constructor also stays the same, only without registerHandler lines.
Instead of registering handler classes, the Domain overrides the hooks of fflib_SObjectDomain for the events it needs.
The on* hooks are the bridge to the D'fflib handlers: their default implementation calls execute(), which runs the handlers registered for that event.
An override that does not call super therefore bypasses the registered handlers of that event.
Class Boilerplate (BaseHandler anatomy)
The D'fflib Trigger Handler Framework provides a structured way to handle trigger events in Salesforce, ensuring that logic is executed in a predictable and bulkified manner, where the trigger state is easily accessible.
To allow registration, a handler class must extend BaseHandler and implement the appropriate trigger event interfaces
for the events it supports (like BeforeInsert). This opens up the following three (optional virtual) methods for implementation:
| Method | Purpose |
|---|---|
1. initialize(state, uow) | Runs once. Retrieval of data or eligibility checks before processing the records. |
2. process(current, previous, uow) | Runs per record. Perform logic and e.g. register to unit of work. No SOQL or DML. Return true if the record was processed, false to skip |
3. finalize(state, uow) | Runs once. Wrapping up, logging, additional data retrieval or registration. |
public inherited sharing class CalculateTotalPrice extends BaseHandler implements BeforeInsert, BeforeUpdate{
// Called once before record iteration — use for bulk queries and setup
public override void initialize( TriggerState ts, dfflib_ISObjectUnitOfWork uow ){
// e.g. pre-load related records from a selector
}
// Called once per record — no SOQL, no DML
public override Boolean process( SObject current, SObject original, dfflib_ISObjectUnitOfWork uow ){
RoomReservation__c newRecord = ( RoomReservation__c ) current;
RoomReservation__c oldRecord = ( RoomReservation__c ) original;
// register work on uow, return true if this record was processed
return true;
}
// Called once after record iteration
public override void finalize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){
// e.g. call Domain method, Log
}
}Trigger Handler Execution Order
The D'fflib Trigger Handler Framework executes the methods of the registered handlers in a specific order:
- All
initialize()methods are called, to guarantee all setup or eligibility checks are performed on the original trigger state, before records are possibly modified - All
process()methods are called for each record - All
finalize()methods are executed.
In pseudocode, this looks like:
// initialize unit of work
// loop over handlers
handler.initialize( triggerState, uow );
// loop over handlers
// loop over records
handler.process( record, previousRecord, uow );
// loop over handlers
handler.finalize( triggerState, uow );
// commit unit of workInstead of handlers extending the BaseHandler, fflib provides overridable hooks in the Domain class.
They hold all records of the transaction in one call, so looping, querying and registering is done in the same method.
There are dispatchers that call these hooks in a specific order during the trigger execution. Despite the ability to override dispatchers, it's generally recommended to initially only override hooks for consistent behaviour.
| Dispatcher | Hooks (in call order) | D'fflib equivalent |
|---|---|---|
handleBeforeInsert() | 1. onApplyDefaults()2. onBeforeInsert() | BeforeInsert handler |
handleBeforeUpdate() | 1. onBeforeUpdate() | BeforeUpdate handler |
handleBeforeDelete() | 1. onBeforeDelete() | BeforeDelete handler |
handleAfterInsert() | 1. CRUD check (create) 2. onValidate()3. onAfterInsert() | AfterInsert handler |
handleAfterUpdate() | 1. CRUD check (update) 2. onValidate()3. onAfterUpdate() | AfterUpdate handler |
handleAfterDelete() | 1. CRUD check (delete) 2. onAfterDelete() | AfterDelete handler |
handleAfterUndelete() | 1. CRUD check (undelete) 2. onAfterUndelete() | AfterUndelete handler |
- The CRUD check (step 0) only runs in the after dispatchers. It throws a
DomainExceptionwhen the user lacks the permission, unless disabled viaConfiguration.disableTriggerCRUDSecurity(). - Validation runs in the after phase, there is no validate hook before the DML.
Concepts and examples
Lifecycle flexibility
A trigger handler often requires two loops, one for collecting necessary data and another for processing the records. Therefore, there are multiple ways to implement the same business logic. In the use-case when needing to register work based on the parents' values, you can:
- loop over records in
initialize()to fetch parent-Ids, query; and then register inprocess() - loop over records in
process(), and query and loop infinalize()
There isn't a single correct approach. The choice depends on the specific requirements and the desired trigger behaviour.
Which could be dependent on need to share data across phases
or based on the eligibility by trigger handler execution order. Most commonly, all eligibility checks
and data collection are done in initialize().
public inherited sharing class CalculateTotalPrice extends BaseHandler implements BeforeInsert, BeforeUpdate, FireOnce{
private Map<Id, Room__c> roomsById;
public override void initialize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){
Set<Id> roomIds = new Set<Id>();
// Loop Reservations to collect Room__c Ids
for( Integer i = 0, j = state.currentList.size(); i < j; i++ ){
RoomReservation__c res = ( RoomReservation__c ) state.currentList[ i ];
if( res.Room__c != null ){
roomIds.add( res.Room__c );
}
}
// Query Rooms and group them by Id for easy retrieval
roomsById = new Map<Id, Room__c>(
( List<Room__c> ) SEL_Rooms.newInstance( dfflib_Database.Context.NONE ).selectSObjectsById( roomIds )
);
}
public override Boolean process( SObject current, SObject previous, dfflib_ISObjectUnitOfWork uow ){
RoomReservation__c res = ( RoomReservation__c ) current;
Room__c room = roomsById.get( res.Room__c );
if( room != null && res.CheckInDate__c != null && res.CheckOutDate__c != null ){
Integer nights = res.CheckInDate__c.daysBetween( res.CheckOutDate__c );
if( nights > 0 ){
res.TotalPrice__c = room.PricePerNight__c * nights;
}
}
return true;
}
}public inherited sharing class ValidateDeactivation extends BaseHandler implements BeforeUpdate, FireOnce{
Set<Id> deactivatedRoomIds = new Set<Id>();
// Collect the records that changed from active to inactive.
// Since records should be checked for changed AND currently being inactive,
// getChangedRecords() would cause a duplicate loop, therefore performing in process()-loop
public override Boolean process( SObject current, SObject previous, dfflib_ISObjectUnitOfWork uow ){
Room__c curr = ( Room__c ) current;
Room__c prev = ( Room__c ) previous;
if( curr.IsActive__c == false && prev.IsActive__c == true ){
deactivatedRoomIds.add( curr.Id );
}
return true;
}
// One aggregate query for all collected records, optionally adding errors
public override void finalize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){
if( deactivatedRoomIds.size() > 0 ){
List<dfflib_AggregateResult> numOpenReservationsPerRoom = SEL_RoomReservations
.newInstance( dfflib_Database.Context.NONE )
.selectOpenCountPerRoomId( deactivatedRoomIds );
Map<Id, Room__c> roomsById = new Map<Id, Room__c>( ( List<Room__c> ) state.currentList );
for( Integer i = 0, j = numOpenReservationsPerRoom.size(); i < j; i++ ){
dfflib_AggregateResult result = numOpenReservationsPerRoom[ i ];
Id roomId = ( Id ) result.get( 'Room__c' );
if( Integer.valueOf( result.get( 'numOpenReservations' ) ) > 0 ){
Room__c roomToSetError = roomsById.get( roomId );
roomToSetError.addError( 'Cannot deactivate a room with open reservations.' );
}
}
}
}
}A hook is a single method: there are no separate phases. Collecting Ids, querying and processing the records all happen inside the one hook, in the order you write them.
Keep queries outside the record loop, as in initialize(). Data shared between steps is held in local variables or fields on the Domain.
The D'fflib phases make this structure explicit, and keep process() free of queries.
Trigger State
The trigger framework constructs the Domain in the before phase. With TriggerState enabled, that same Domain instance is kept and reused in the after phase
(with its records refreshed), instead of constructing a new one. Domain instance fields therefore survive from the before to the after phase, e.g. an expensive query result.
The Domain is recursion-aware: when DML in a handler fires the trigger again, the nested invocation gets a fresh Domain instance, and the outer one is restored afterwards.
Enabled by default in D'fflib
The D'fflib Domain constructor super( sObjectList, uow ) enables Trigger State. Only a Domain constructed with super( sObjectList ) has it disabled.
Handler instances are not kept: they are instantiated for every event execution, so handler fields only live within that one event.
Trigger State is disabled by default. Without it, every trigger phase works on a new Domain instance, so a field set in onBeforeInsert() is empty in onAfterInsert().
Enable (or disable) it in the Domain constructor, directly after super():
public Rooms( List<Room__c> rooms ){
super( rooms );
Configuration.enableTriggerState(); // Configuration.disableTriggerState() to turn it off again
}Access control
- For Selectors, the
dfflib_Database.Contextis specified upon selector initiation, like normal usage, thus in full control of the handler. - For Unit of Work, by default, every trigger handler shares the same instance injected by the framework, which is constructed upon Domain initialisation.
All changes across all handlers commit in one transaction. There are two ways to control the context of the Unit of Work:
- To control for all handlers at once, specify the Context in the Domain constructor
public DOM_Rooms( List<Room__c> sObjectList ){ super( sObjectList, dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ) ); // ... Handler registration } - To deviate for only one Handler, control within that handler, by initiating a separate Unit of Work with the desired
dfflib_Database.Context. Which implies, all transaction management, including Exception handling and commit becomes the handlers' responsibility.public without sharing class SyncProductMinMaxPrices extends BaseHandler implements BeforeInsert, BeforeUpdate, FireOnce{ private Map<Id, Product2> products; private final Set<Id> productIdsRequiringValidation = new Set<Id>(); private dfflib_ISObjectUnitOfWork uowSystemMode; // Gather Product IDs from trigger state records public override void initialize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){ this.uowSystemMode = dfflib.unitOfWork.newInstance( dfflib_Database.Context.NONE ); Set<Id> productIds = new Set<Id>(); for( Integer i = 0, j = state.currentList.size(); i < j; i++ ){ productIds.add( ( ( ProductSupplierPrice__c ) state.currentList[ i ] ).Product__c ); } products = new Map<Id, Product2>( SEL_Products.newInstance( dfflib_Database.Context.NONE ) .selectSummaryPriceFieldsByIds( productIds ) ); } // Per-record logic — register dirty records to UoW public override Boolean process( SObject current, SObject previous, dfflib_ISObjectUnitOfWork uow ){ ProductSupplierPrice__c psp = ( ProductSupplierPrice__c ) current; Product2 parentProd = products.get( psp.Product__c ); // Validate whether new lowest price, if so, update on Parent Product if( parentProd.Min_Supplier_Purchase_Price__c == null || psp.Min_Supplier_Purchase_Price__c < parentProd.Min_Supplier_Purchase_Price__c ){ parentProd.Min_Supplier_Purchase_Price__c = psp.Min_Supplier_Purchase_Price__c; this.uowSystemMode.registerDirty( parentProd, new List<SObjectField>{ Product2.Min_Supplier_Purchase_Price__c } ); } // ... Track products that require validation and add to productIdsRequiringValidation return true; } public override void finalize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){ // Cross-Domain calls belong in finalize, after all records are processed if( !productIdsRequiringValidation.isEmpty() ){ DOM_Products.newInstance().validateMinMaxSupplierCurrencies( productIdsRequiringValidation, this.uowSystemMode ); } try{ this.uowSystemMode.commitWork(); } catch( Exception e ){ // Handle exception as needed } } }
- To control for all handlers at once, specify the Context in the Domain constructor
It's best-practice to always declare a sharing mode for classes, and also for the (inner) trigger handler classes.
When a Unit of Work is run with System Mode, it will still respect the sharing mode of the class in which it is executed.
By declaring the sharing mode explicitly, it is clearer under which context the database transactions are expected.
Since the trigger hooks live within the Domain, there is no distinction between the Domain and its handlers in terms of access control.
However, there is one mechanism to optionally bypass the object-permission (CRUD) checks of the after hooks, by calling
Configuration.disableTriggerCRUDSecurity() in the Domain constructor. This can only be disabled per SObjectType and not per dispatcher or hook.
Share data across phases and handlers
Within one handler, instance variables carry data across the phases (initialize, process, finalize), as ValidateDeactivation does with deactivatedRoomIds
or SyncProductMinMaxPrices with products and uowSystemMode. This avoids static state and additional queries.
Handlers of the same trigger event can build on each other's record changes, but mind the execution order of the framework. If a handler changes a value on a TriggerState record, the next handler will automatically see the change. Handlers hold no reference to each other, so data other than the records themselves has to be exchanged through a shared holder, e.g. a static member on the Domain class, which is best kept to a minimum.
Detect changed records
In an update trigger every record of the transaction reaches your handler, whether or not the fields you care about were touched.
The Domain's getChangedRecords() narrows the scope to the records where at least one of the given fields differs from its previous value,
so downstream queries and loops only run when needed. It's available to both D'fflib handlers and fflib hooks, since it is a method of dfflib_SObjectDomain itself.
public override void initialize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){
List<Room__c> changedRooms = ( List<Room__c> ) getDomain().getChangedRecords(
new Set<SObjectField>{ Room__c.IsActive__c }
);
// Query and prepare only for changedRooms
}While it is recommended to pass a strongly typed set of SObjectFields to getChangedRecords(), the method also accepts a set of field names as strings.
Inside a hook the method is called directly on the Domain and not from a handler sub-class. Therefore there is no need to call getDomain():
public override void onBeforeUpdate( Map<Id, SObject> existingRecords ){
List<Room__c> changedRooms = ( List<Room__c> ) getChangedRecords(
new Set<SObjectField>{ Room__c.IsActive__c }
);
}Add record errors
In Apex, it is possible to add an error to a record programmatically using the addError() methods. This prevents the record from being saved:
with the default all-or-none DML, the whole operation fails.
Note, the specified String or Exception will be directly shown to the end-user, so using custom labels for translations etc. is recommended.
[record].addError( 'Lovely error message.' );
[record].addError( 'Lovely <b>error</b> message.', false ); // skip escape, to render HTML in UI
try{
// some code that might throw an exception
} catch( Exception ex ){
[record].addError( ex );
}List<Database.Error> errors = currentRoom.getErrors();
System.Assert.areEqual( 1, errors.size(), 'Expected 1 error for room with open reservations' );
System.Assert.areEqual(
'Cannot deactivate a room with open reservations.',
errors[ 0 ].getMessage(),
'Expected different error message'
);Despite addError() methods existing since Spring '08 (API 12.0), Salesforce only supported asserting errors per Winter '21 (API 50.0), by adding getErrors() and hasErrors() to SObject.
With this introduction, the supporting error registry in dfflib_SObjectDomain has become obsolete and is marked @deprecated. It's encouraged to move away from
[record].addError( error( 'Some error message', [record] ) ) and dfflib_SObjectDomain.Errors.getAll().
FireOnce
Handlers that implement FireOnce are only executed once per record per transaction.
For records where process() returns true, this is skipped on any subsequent trigger invocation within the same transaction,
e.g. for when the same record would be triggered again via another trigger, Flow or own DML.
public inherited sharing class CalculateTotalPrice extends BaseHandler implements BeforeInsert, BeforeUpdate, FireOnce{
// ...
}Notes:
FireOnceis tracked per handler-event combination. Thus if one handler is set for both before and after events, it will track separately for each event.FireOnceis only tracked within one transaction, implying that each transaction will start fresh and process all records.- When all records have been processed, the full handler will be skipped, including
initialize()andfinalize(). - When re-evaluation is needed for potential eligibility-revisits due to field-changes, return
falseor don't implementFireOncefor that handler.
Testing a Trigger
See the Testing & Mocking article for full details on setting up mocks, stubs, and ApexMocks used across all layers.
Trigger
In a codebase which fully adopted (D')fflib, SObjects might not be inserted or updated during unit tests. When such SObjects do have a trigger implemented,
these triggers will have a 0% test coverage and thus cause deployments to fail.
While we're defensive on adding code "just for the sake of code coverage", for this situation we either recommend to add an end-to-end unit test, or create one class which only performs inserts for all SObjects with a trigger, to prevent unexpected deployment failures. Like TriggersTest.
Handler
The framework provides runHandler() to execute a specific handler for a given trigger event in isolation. Implying no construction of Domain, trigger execution or DML.
@IsTest
private static void calculateTotalPrice_validRoomAndDates(){
// create mocks
fflib_ApexMocks mocks = new fflib_ApexMocks();
dfflib_ISObjectUnitOfWork uowMock = dfflib.unitOfWork.defineMock( mocks );
SEL_Rooms m_selRooms = ( SEL_Rooms ) dfflib.selector.defineMock(
mocks, SEL_Rooms.class, Room__c.SObjectType
);
// Given - Room with PricePerNight = 42.0 and Reservation for 3 nights
DOM_RoomsTest.Builder roomBuilder = TestFactory.aRoom().asSingleRoom( 101 );
RoomReservation__c res = ( RoomReservation__c ) TestFactory.aRoomReservation()
.asDefault()
.forRoom( roomBuilder )
.withDates( Date.today(), Date.today().addDays( 3 ) )
.mockWithIds();
Room__c room = ( Room__c ) roomBuilder.mockWithIds();
// set mocks
mocks.startStubbing();
mocks.when( m_selRooms.sObjectType() ).thenReturn( Room__c.SObjectType );
mocks.when( m_selRooms.selectSObjectsById( new Set<Id>{ res.Room__c } ) )
.thenReturn( new List<Room__c>{ room } );
mocks.stopStubbing();
// When - Run the CalculateTotalPrice handler for BEFORE_INSERT
new DOM_RoomReservations( new List<RoomReservation__c>{ res } ).runHandler(
DOM_RoomReservations.CalculateTotalPrice.class,
dfflib_SObjectDomain.TriggerEvent.BEFORE_INSERT,
null,
uowMock
);
// Then - TotalPrice should be PricePerNight (42.0) x 3 nights = 126.0
System.Assert.areEqual( 126.0, res.TotalPrice__c, 'Expected TotalPrice = PricePerNight x nights' );
}For update events, the previous records can be passed as third argument (Map<Id, Room__c> oldMap), like in DOM_RoomsTest.
To assert hook-execution and logic in fflib, you can leverage the MockDatabase, which emulates a DML operation without performing it.
How it works
- Seed the mock via
fflib_SObjectDomain.Test.Database:onInsert( records ),onUpdate( records, oldRecords ),onDelete( recordsById )oronUndelete( records ). Each call selects one operation and clears the flags of the others. - Invoke
fflib_SObjectDomain.triggerHandler( DOM_Rooms.class ), the exact call the trigger makes. In a test with seeded records it reads the mock instead ofTrigger.new/Trigger.oldMap. - Replay: the framework constructs the Domain via its
Constructor, then runs the before phase and the after phase back to back on the seeded records. - Assert on the records, e.g. defaults applied in the before phase, or errors via
getErrors().
For updates, existingRecords (and with that getChangedRecords()) is served from the old records given to onUpdate().
@IsTest
private static void onValidate_inactiveRoom(){
// Given - set data
Room__c current = new Room__c();
current.Id = fflib_IDGenerator.generate( Room__c.SObjectType );
current.Capacity__c = 1;
current.IsActive__c = true;
current.Name = 'ROOM-00101';
current.PricePerNight__c = 40.2;
current.RoomType__c = DOM_Rooms.TYPE_SINGLE;
Room__c previous = current.clone( true );
current.IsActive__c = false;
// set mocks
fflib_SObjectDomain.Test.Database.onUpdate(
new List<Room__c>{ current }, new Map<Id, SObject>{ previous.Id => previous }
);
// When - invoke the trigger handler
fflib_SObjectDomain.triggerHandler( DOM_Rooms.class );
// Then - assert expectation
System.Assert.isTrue( current.getErrors().isEmpty(), 'Expected no errors because of inactive room' );
}Pitfalls
- Nothing is persisted: no Ids are assigned and no before-save changes are applied beyond your handler logic. Seed records with (mocked) Ids when updating or deleting.
- The mock keeps the state of earlier calls:
onInsert()does not clear previous old records andonDelete()does not clear previous records. Use one scenario per test method. - While the mock holds records, every
triggerHandler()call in that test uses it, so real DML in the same test does not run the real trigger path. - The after-phase CRUD check applies to the running test user, and events disabled via
getTriggerEvent()are skipped. - Triggers are not covered by this approach; the single real DML in
TriggersTestremains required. - Dependencies of the Domain (Unit of Work, selectors) still need to be mocked, see Testing & Mocking.
runHandler() | MockDatabase | |
|---|---|---|
| Scope | One registered D'fflib handler | Whole Domain: hooks, dispatchers and registered handlers |
| Trigger events | One chosen event | Before and after phase of the seeded operation |
| Typical use | Handler logic | Hook-based Domains, getChangedRecords(), end-to-end Domain flow without DML |
Migration steps
Both fflib hooks and D'fflib handlers can coexist, though it's recommended to apply consistency and choose one trigger construct. To migrate existing fflib hooks to D'fflib handlers to untangle nested logic and fully adopt the D'fflib approach, follow the steps outlined below.
Trigger
- Change reference from
fflib_SObjectDomaintodfflib_SObjectDomain. Since this is backward compatible, this can be done without an immediate change to the existing hook- and dispatcher-overrides.dfflib_SObjectDomain.triggerHandler( DOM_Rooms.class );
Domain enabler
-
Ensure Domain extends D'fflib, as documented in Domains migration guide.
-
Enable Trigger Handler Framework Extend the
super( SObjectList )in the Domain constructor with a Unit of Work instance. This gives control to define the desireddfflib_Database.Contextfor all Trigger Handler DML operations. Additionally, this instructs the Domain to enable the Handler Framework, likeenableTriggerState(), which improves performance by keeping the Domain instance consistent across Trigger Events.public DOM_Rooms( List<Room__c> sObjectList ){ // Initialize the domain super( sObjectList, dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ) ); // ... Handler registration }
Hook to handler migration
- Pick one
on*hook or dispatcher override in the Domain
Preferably one that has grown large or is hard to test. - Create a handler class named after its single-responsibility, extending
BaseHandlerand implementing the event interface (e.g.BeforeInsert) andFireOncewhen desired. - Move the logic into the handler
The record loop becomesprocess(), queries move toinitialize(), and DML becomes registration on the injected Unit of Work. Optionally prefixgetDomain().to reference Domain methods likegetChangedRecords(). - Add
registerHandler( TriggerEvent.<EVENT>, <Handler>.class )to the Domain constructor and remove the hook override
Note, this can only be done when the Domain has been migrated, and thus extends the D'fflib dfflib_SObjectDomain.
Test class changes
- Replace the
MockDatabasetest of the migrated hook with arunHandler()test - Keep one real DML test for the Trigger itself, see Trigger coverage
Testing & Mocking
Elaborating on the benefits of mocking, and how to properly set up test data to mock methods with. Including thorough and extensive example code snippets.
Unit of Work
Step-by-step guide on how to set up and interact with the Unit of Work, maximise the functions and benefits, while being aware of edge cases and D'fflib-specific functionalities.