Trigger Handler - wimvelzeboer/fflib-apex-extensions GitHub Wiki
The trigger handler is responsible for invoking the correct trigger actions for the occurred TriggerOperation. It read the configured Trigger Actions from the Custom Metadata Object fflib_TriggerAction__mdt, and is using the UnitOfWork to execute each Trigger Action (as implementation of fflib_IDoWork).
A trigger action executes the required business logic that needs to happen after a specific TriggerOperation has occurred.
Use the plural name of your Custom Object for the name of your trigger action appended with 'TriggerAction'.
The methods names are typically constructed from the following three elements;
-
EventType for object
-
condition
-
business logic
The condition can be omitted when the business logic need to be performed on all records.
Some examples of valid names are:
onChangedEmployeeNumberForPartnerAccountsDoRecalculateDiscount
<-------- 1 ----------><------- 2 ------><-------- 3 -------->
onChangedEmployeeNumberDoRecalculateRating
<-------- 1 ----------><------- 3 ------->
The methods will also process the logic in the same order:
-
Validate that there are records meeting the event criteria
They use the methodgetChangedRecords
followed by a guard clause to halt further execution when there are no records meeting the criteria -
Validate the condition
Typically creating a new domain with the changedRecords and using one or more selector methods from the domain
followed by a guard clause to halt further execution when there are no records in the domain meeting the condition -
Invoke business logic
Either invokes a business logic method on the domain, if the scope is limited to the contents of a domain. Otherwise it invokes a service layer method, passing the domain as argument.
In this example you see a trigger action executed in real-time:
public with sharing class TA_Account_RecalculateRating
extends fflib_TriggerAction
{
public override void onBeforeInsert()
{
recalculateRating();
}
public override void onBeforeUpdate()
{
onChangedNumberOfEmployeesRecalculateRating();
}
private void onChangedNumberOfEmployeesRecalculateRating()
{
List<SObject> changedRecords =
triggerContext.getChangedRecords(Schema.Account.NumberOfEmployees);
if (changedRecords.isEmpty()) return;
Accounts.newInstance(changedRecords)
.recalculateRating();
}
private void recalculateRating()
{
Accounts.newInstance(triggerContext.getRecords())
.recalculateRating();
}
}