- Notifications
You must be signed in to change notification settings - Fork178
A framework for partitioning, ordering, and bypassing trigger logic for applications built on Salesforce.
License
mitchspano/trigger-actions-framework
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The Apex Trigger Actions Framework allows developers and administrators to partition, order, and bypass record-triggered automations for applications built on Salesforce.com.
The framework supports both Apex and Flow - which empowers developers and administrators to define automations in the tool of their choice, then plug them together harmoniously.
With granular control of the relative order of execution of Apex vs. Flow and standardized bypass mechanisms, the framework enables an "Automation Studio" view ofall automations for a given sObject.
With the Trigger Actions Framework, we usecustom metadata to configure our trigger logic from the setup menu. The custom metadata defines:
- The sObject and context for which an action is supposed to execute
- The order to take those actions within a given context
- Mechanisms to determine if and when the action should bebypassed
The related lists on theSObject_Trigger_Setting__mdt
record provide a consolidated and ordered view ofall of the Apex and Flow actions that will be executed when a record is inserted, updated, deleted, or undeleted:
The Trigger Actions Framework conforms strongly to theOpen–closed principle and theSingle-responsibility principle. To add or modify trigger logic in our Salesforce org, we won't need to keep modifying the body of a TriggerHandler class; we can create a class or a flow with responsibility scoped to the automation we are trying to build and configure these actions to run in a specified order within a given trigger context.
The work is performed in theMetadataTriggerHandler
class which implements theStrategy Pattern by fetching all Trigger Action metadata that is configured in the org for the given trigger context and usesreflection to dynamically instantiate an object that implements a `TriggerAction`` interface, then casts the object to the appropriate interface as specified in the metadata and calls the respective context methods in the order specified.
Note that if an Apex class is specified in metadata and it does not exist or does not implement the correct interface, a runtime error will occur.
To get started, call theMetadataTriggerHandler
class within the body of the trigger of the sObject:
triggerOpportunityTriggeronOpportunity (beforeinsert,afterinsert,beforeupdate,afterupdate,beforedelete,afterdelete,afterundelete) {newMetadataTriggerHandler().run();}
Next, create a row in theSObject_Trigger_Setting__mdt
custom metadata type which corresponds to the sObject that we want to enable usage of the framework on - in this case, it would be Opportunity.
To define a specific action, we write an individual class which implements the applicable interface(s):
publicclassTA_Opportunity_StageInsertRulesimplementsTriggerAction.BeforeInsert {@TestVisibleprivatestaticfinalStringPROSPECTING ='Prospecting';@TestVisibleprivatestaticfinalStringINVALID_STAGE_INSERT_ERROR ='The Stage must be \'Prospecting\' when an Opportunity is created';publicvoidbeforeInsert(List<Opportunity>triggerNew){for (Opportunityopp :triggerNew) {if (opp.StageName !=PROSPECTING) {opp.addError(INVALID_STAGE_INSERT_ERROR); } } }}
Then create a row within theTrigger_Action__mdt
custom metadata type to call the action in the specified order on the sObject.
The Apex Trigger Actions Framework can also allow you to invoke a flow by name, and determine the order of the flow's execution amongst other trigger actions in a given trigger context. Here is an example of a trigger action flow that checks if a record's name has changed and if so it sets the record's description to a default value.
To make your flows usable, they must be auto-launched flows and you need to create the following flow resource variables:
Variable Name | Variable Type | Available for Input | Available for Output | Description | Available Contexts |
---|---|---|---|---|---|
record | record | yes | yes | the new version of the record in the DML operation | insert, update, undelete |
recordPrior | record | yes | no | the old version of the record in the DML operation | update, delete |
To enable this flow, simply insert a trigger action record withApex_Class_Name__c
equal toTriggerActionFlow
and set theFlow_Name__c
field with the API name of the flow itself. You can select theAllow_Flow_Recursion__c
checkbox to allow flows to run recursively (advanced).
Warning
Trigger Action Flows and Recursion Depth
- Key Point: Trigger Action Flows are executed using the
Invocable.Action
class and are therefore subject to the (undocumented) "maximum recursion depth of 3" which is lower than the usualtrigger depth limit of 16. - Why It Matters: This limit can be reached when Trigger Action Flows perform DML operations that cascade across multiple objects with their own Trigger Action Flows.
- When to Be Careful: Exercise caution when using Trigger Action Flows in scenarios involving multiple DML operations or complex trigger chains.
- Safe Use Cases: Same-record updates, using the
addError
action to add a custom error message, and actions like workflow email alerts are generally safe. - How to Avoid Issues: ImplementingEntry Criteria Formula will reduce the likelihood of hitting the limit. Define entry criteria on all Flow actions whenever possible.
Trigger Action Flows can also be used to process Change Data Capture events, but there are two minor modifications necessary:
Variable Name | Variable Type | Available for Input | Available for Output | Description |
---|---|---|---|---|
record | record | yes | no | the changeEvent object |
header | FlowChangeEventHeader (Apex Defined) | yes | no | a flow-accessible version of theChangeEventHeader object |
Create a trigger action record withApex_Class_Name__c
equal toTriggerActionFlowChangeEvent
(instead ofTriggerActionFlow
) and set theFlow_Name__c
field with the API name of the flow itself.
Individual trigger actions can have their own dynamic entry criteria defined in a simple formula.This is a new feature and is built using theFormulaEval
namespace within Apex.
To define an entry criteria formula for a given trigger action, first define a class which extendsTriggerRecord
for the specific SObject type of interest.This class must be global and contains two global properties:record
andrecordPrior
which get their value fromnewSObject
andoldSObject
downcast to the proper concrete SObject type. Below is an example of this class for theAccount
sObject:
globalclassAccountTriggerRecordextendsTriggerRecord {globalAccountrecord {get {return (Account)this.newSObject; } }globalAccountrecordPrior {get {return (Account)this.oldSObject; } }}
Then enter the API name of that class in theSObject_Trigger_Setting__mdt.TriggerRecord_Class_Name__c
field on theSObject_Trigger_Setting__mdt
record of interest.
Now, you can define a formula on theTrigger_Action__mdt
record which operates on an instance of this class at runtime to determine if a record should be processed
record.Name = "Bob" && recordPrior.Name = "Joe"
Note
If the entry criteria field is null, the system will act as if there are no entry criteria and will process all records.
Now, the automation will only execute for any records within the transaction for which the name used to be "Joe", but it is changed to "Bob".
Important
- Field Traversal Limitations: The
record
andrecordPrior
objects within the formula are limited to the fields directly available on the record itself. Cross-object traversal, such asrecord.RecordType.DeveloperName
, is not supported.
The Trigger Actions Framework supports standard objects, custom objects, and objects from installed packages. To use the framework with an object from an installed package, separate the Object API Name from the Object Namespace on the sObject Trigger Setting itself. For example, if you want to use the Trigger Actions Framework on an sObject calledAcme__Explosives__c
, configure the sObject Trigger Setting like this:
Object Namespace | Object API Name |
---|---|
Acme | Explosives__c |
Use theTriggerBase.idToNumberOfTimesSeenBeforeUpdate
andTriggerBase.idToNumberOfTimesSeenAfterUpdate
to prevent recursively processing the same record(s).
publicclassTA_Opportunity_RecalculateCategoryimplementsTriggerAction.AfterUpdate {publicvoidafterUpdate(List<Opportunity>triggerNew,List<Opportunity>triggerOld) {Map<Id,Opportunity>oldMap =newMap<Id,Opportunity>(triggerOld);List<Opportunity>oppsToBeUpdated =newList<Opportunity>();for (Opportunityopp :triggerNew) {if (TriggerBase.idToNumberOfTimesSeenAfterUpdate.get(opp.id) ==1 &&opp.StageName !=oldMap.get(opp.id).StageName ) {oppsToBeUpdated.add(opp); } }if (!oppsToBeUpdated.isEmpty()) {this.recalculateCategory(oppsToBeUpdated); } }privatevoidrecalculateCategory(List<Opportunity>opportunities) {//do some stuffupdateopportunities; }}
The framework provides standardized bypass mechanisms to control execution on either an entire sObject, or for a specific action.
To bypass from the setup menu, simply navigate to the sObject Trigger Setting or Trigger Action metadata record you are interested in and check the Bypass Execution checkbox.
These bypasses will stay active until the checkbox is unchecked.
You can bypass all actions on an sObject as well as specific Apex or Flow actions for the remainder of the transaction using Apex or Flow.
To bypass from Apex, use the staticbypass(String name)
method in theTriggerBase
,MetadataTriggerHandler
, orTriggerActionFlow
classes.
publicvoidupdateAccountsNoTrigger(List<Account>accountsToUpdate) {TriggerBase.bypass('Account');updateaccountsToUpdate;TriggerBase.clearBypass('Account');}
publicvoidinsertOpportunitiesNoRules(List<Opportunity>opportunitiesToInsert) {MetadataTriggerHandler.bypass('TA_Opportunity_StageInsertRules');insertopportunitiesToInsert;MetadataTriggerHandler.clearBypass('TA_Opportunity_StageInsertRules');}
publicvoidupdateContactsNoFlow(List<Contacts>contactsToUpdate) {TriggerActionFlow.bypass('Contact_Flow');updatecontactsToUpdate;TriggerActionFlow.clearBypass('Contact_Flow');}
To bypass from Flow, use theTriggerActionFlowBypass.bypass
invocable method. You can set theBypass Type
toApex
,Object
, orFlow
, then pass the API name of the sObject, class, or flow you would like to bypass into theName
field.
Flow | Invocable Action Setup |
---|---|
![]() | ![]() |
The Apex and Flow bypasses will stay active until the transaction is complete or until cleared using theclearBypass
orclearAllBypasses
methods in theTriggerBase
,MetadataTriggerHandler
, orTriggerActionFlow
classes. There are also corresponding invocable methods in theTriggerActionFlowClearBypass
andTriggerActionFlowClearAllBypasses
which will perform the same resetting of the bypass. To use these invocable methods, set thebypassType
toApex
,Object
, orFlow
, then to clear a specific bypass set the API name of the sObject, class, or flow you would like to clear the bypass for into thename
field.
Both thesObject_Trigger_Setting__mdt
and theTrigger_Action__mdt
have fields calledBypass_Permission__c
andRequired_Permission__c
. Both of these fields are optional, but they can control execution flow for specific users.
Developers can enter the API name of a permission in theBypass_Permission__c
field. If this field has a value, then the trigger/action will be bypassed if the running user has the custom permission identified. This can be helpful when assigned to an integration service-account user to facilitate large data loads, or when assigned to a system administrator for a one-time data load activity.
Developers can enter the API name of a permission in theRequired_Permission__c
field. If this field has a value, then the trigger/action will only execute if the running user has the custom permission identified. This can allow for new functionality to be released to a subset of users.
It could be the case that multiple triggered actions on the same sObject require results from a query to implement their logic. In order to avoid making duplicative queries to fetch similar data, use the Singleton pattern to fetch and store query results once then use them in multiple individual action classes.
publicclassTA_Opportunity_Queries {privatestaticTA_Opportunity_Queriesinstance;privateTA_Opportunity_Queries() { }publicstaticTA_Opportunity_QueriesgetInstance() {if (TA_Opportunity_Queries.instance ==null) {TA_Opportunity_Queries.instance =newTA_Opportunity_Queries(); }returnTA_Opportunity_Queries.instance; }publicMap<Id,Account>beforeAccountMap {get;privateset; }publicclassServiceimplementsTriggerAction.BeforeInsert {publicvoidbeforeInsert(List<Opportunity>triggerNew) {TA_Opportunity_Queries.getInstance().beforeAccountMap =getAccountMapFromOpportunities(triggerNew ); }privateMap<Id,Account>getAccountMapFromOpportunities(List<Opportunity>triggerNew ) {Set<Id>accountIds =newSet<Id>();for (OpportunitymyOpp :triggerNew) {accountIds.add(myOpp.AccountId); }returnnewMap<Id,Account>( [SELECTId,NameFROMAccountWHEREIdIN :accountIds] ); } }}
Now configure the queries to be the first action to be executed within the given context, and the results will be available for any subsequent triggered action.
With theTA_Opportunity_Queries
class configured as the first action, all subsequent actions can useTA_Opportunity_Queries.getInstance()
to fetch the query results.
publicclassTA_Opportunity_StandardizeNameimplementsTriggerAction.BeforeInsert {publicvoidbeforeInsert(List<Opportunity>triggerNew) {Map<Id,Account>accountIdToAccount =TA_Opportunity_Queries.getInstance() .beforeAccountMap;for (OpportunitymyOpp :triggerNew) {StringaccountName =accountIdToAccount.get(myOpp.AccountId)?.Name;myOpp.Name =accountName !=null ?accountName +' | ' +myOpp.Name :myOpp.Name; } }}
Note:In the example above, the top-level class is the implementation of the Singleton pattern, but we also define an inner class calledService
which is the actual Trigger Action itself. When using this pattern for query management, theApex_Class_Name__c
value on theTrigger_Action__mdt
row would beTA_Opportunity_Queries.Service
.
To avoid having to downcast fromMap<Id,sObject>
, we simply construct a new map out of ourtriggerNew
andtriggerOld
variables:
publicvoidbeforeUpdate(List<Opportunity>triggerNew,List<Opportunity>triggerOld) {Map<Id,Opportunity>newMap =newMap<Id,Opportunity>(triggerNew);Map<Id,Opportunity>oldMap =newMap<Id,Opportunity>(triggerOld); ...}
This will help the transition process if you are migrating an existing Salesforce application to this new trigger actions framework.
Performing DML operations is extremely computationally intensive and can really slow down the speed of your unit tests. We want to avoid this at all costs. Traditionally, this has not been possible with existing Apex Trigger frameworks, but this Trigger Action approach makes it much easier. Included in this project is aTriggerTestUtility
class which allows us to generate fake record Ids.
@IsTestpublicclassTriggerTestUtility {staticIntegermyNumber =1;publicstaticIdgetFakeId(Schema.SObjectTypesObjectType) {Stringresult =String.valueOf(myNumber++);return (Id) (sObjectType.getDescribe().getKeyPrefix() +'0'.repeat(12 -result.length()) +result); }}
We can also usegetErrors()
method to test theaddError(errorMsg)
method of theSObject
class.
Take a look at how both of these are used in theTA_Opportunity_StageChangeRulesTest
class:
@IsTestprivatestaticvoidinvalidStageChangeShouldPreventSave() {List<Opportunity>triggerNew =newList<Opportunity>();List<Opportunity>triggerOld =newList<Opportunity>();//generate fake IdIdmyRecordId =TriggerTestUtility.getFakeId(Opportunity.SObjectType);triggerNew.add(newOpportunity(Id =myRecordId,StageName =Constants.OPPORTUNITY_STAGENAME_CLOSED_WON ) );triggerOld.add(newOpportunity(Id =myRecordId,StageName =Constants.OPPORTUNITY_STAGENAME_QUALIFICATION ) );newTA_Opportunity_StageChangeRules().beforeUpdate(triggerNew,triggerOld);//Use getErrors() SObject method to get errors from addError without performing DMLSystem.assertEquals(true,triggerNew[0].hasErrors(),'The record should have errors' );System.assertEquals(1,triggerNew[0].getErrors().size(),'There should be exactly one error' );System.assertEquals(triggerNew[0].getErrors()[0].getMessage(),String.format(TA_Opportunity_StageChangeRules.INVALID_STAGE_CHANGE_ERROR,newList<String>{Constants.OPPORTUNITY_STAGENAME_QUALIFICATION,Constants.OPPORTUNITY_STAGENAME_CLOSED_WON } ),'The error should be the one we are expecting' );}
Notice how we performedzero DML operations yet we were able to cover all of the logic of our class in this particular test. This can help save a lot of computational time and allow for much faster execution of Apex tests.
The Apex Trigger Actions Framework now has support for a novel feature not found in other Trigger frameworks; DML finalizers.
A DML finalizer is a piece of code that executesexactly one time at the very end of a DML operation.
This is notably different than the final action within a given trigger context. The final configured action can be executed multiple times in case of cascading DML operations within trigger logic or when more than 200 records are included in the original DML operation. This can lead to challenges when capturing logs or invoking asynchronous logic.
DML finalizers can be very helpful for things such asenqueuing a queuable operation orinserting a collection of gathered logs.
Finalizers within the Apex Trigger Actions Framework operate using many of the same mechanisms. First, define a class that implements theTriggerAction.DmlFinalizer
interface. Include public static variables/methods so that the trigger actions executing can register objects to be processed during the finalizer's execution.
publicwithsharingclassOpportunityCategoryCalculatorimplementsQueueable,TriggerAction.DmlFinalizer {privatestaticList<Opportunity>toProcess =newList<Opportunity>();privateList<Opportunity>currentlyProcessing;publicstaticvoidregisterOpportunities(List<Opportunity>toRecalculate) {toProcess.addAll(toRecalculate); }publicvoidexecute(FinalizerHandler.Contextcontext) {if (!toProcess.isEmpty()) {this.currentlyProcessing =toProcess;System.enqueueJob(this);toProcess.clear(); } }publicvoidexecute(System.QueueableContextqc) {// do some stuff }}
Then create a corresponding row ofDML_Finalizer__mdt
to invoke your finalizer in the order specified.
Finally, use the static variables/methods of the finalizer within your trigger action to register data to be used in the finalizer's execution.
publicwithsharingclassTA_Opportunity_RecalculateCategoryimplementsTriggerAction.AfterUpdate {publicvoidafterUpdate(List<Opportunity>triggerNew,List<Opportunity>triggerOld ) {Map<Id,Opportunity>oldMap =newMap<Id,Opportunity>(triggerOld);List<Opportunity>toRecalculate =newList<Opportunity>();for (Opportunityopp :triggerNew) {if (opp.Amount !=oldMap.get(opp.Id).Amount) {toRecalculate.add(opp); } }if (!toRecalculate.isEmpty()) {OpportunityCategoryCalculator.registerOpportunities(toRecalculate); } }}
Just like everything else within the Apex Trigger Actions Framework, finalizers can be bypassed to suit your needs. On theDML_Finalizer__mdt
metadata record, use theBypass_Execution__c
checkbox to bypass globally and theBypass_Permission__c
/Required_Permission__c
fields to bypass for specific users or profiles.
For static bypasses, call thebypass
,clearBypass
,isBypassed
, andclearAllBypasses
methods within theFinalizerHandler
class.
Warning
DML Finalizers are brand new and should be considered asexperimental. If you encounter any issues when using them, please create an issue on the GitHub repository.
DML Finalizers are not allowed to call any other DML operations; otherwise they wouldn't be able to guarantee their final nature. If a finalizer calls another DML operation, a runtime error will be thrown.
To ensure that cascading DML operations are supported, all configured finalizers within the org are invoked at the end of any DML operation, regardless of the SObject of the original triggering operation.
TheFinalizerHandler.Context
object specified in theTriggerAction.DmlFinalizer
interface'sexecute
method currentlyis empty; there are no properties on this object. We are establishing the interface to include the context to help future-proof the interface's specifications.
To use a DML Finalizer, the Apex Trigger Actions Framework must be enabled on every SObject that supports triggers and will have a DML operation on it during a transaction, and enabled in all trigger contexts on those sObjects. If DML is performed on an SObject that has a trigger that does not use the framework, the system will not be able to detect when to finalize the DML operation.
Detecting when to finalize the operation requires knowledge of the total number of records passed to the DML operation. Unfortunately, there is no bulletproof way to do this currently in Apex; the best thing we can do is to rely onLimits.getDmlRows()
to infer the number of records passed to the DML operation.
This works in most cases, but certain operations (such as setting aSystem.Savepoint
) consume a DML row, and there are certain sObjects where triggers are not supported likeCaseTeamMember
which can throw off the counts and remove our ability to detect when to finalize. In order to avoid this problem, use theTriggerBase.offsetExistingDmlRows()
method before calling the first DML operation within your Apex.
Savepointsp =Database.setSavepoint();// adds to Limits.getDmlRows()TriggerBase.offsetExistingDmlRows();insertaccounts;
insertcaseTeamMembers;// additions to Limits.getDmlRows() are not able to be automatically handled because there is no trigger on `CaseTeamMember`TriggerBase.offsetExistingDmlRows();updatecases;
Note
Please consider upvotingthis idea to help avoid this quirky reliance onLimits.getDmlRows()
It could be the case that you have multiple DML operations in a row and you would like the system to wait to finalize until they are all complete. For example, in a Lightning Web Component's controller:
@AuraEnabledpublicstaticvoidfoo(){Accountacme =newAccount(Name ='Acme' );insertacme;// finalizer is called hereAccountacmeExplosives =newAccount(Name ='Acme-Explosives',ParentId =acme.Id, );insertacmeExplosives;// second finalizer is called here}
To facilitate these needs, call theTriggerBase.waitToFinalize()
andTriggerBase.nowFinalize()
methods:
@AuraEnabledpublicstaticvoidfoo(){TriggerBase.waitToFinalize();Accountacme =newAccount(Name ='Acme' );insertacme;AccountacmeExplosives =newAccount(Name ='Acme-Explosives',ParentId =acme.Id, );insertacmeExplosives;TriggerBase.nowFinalize();// single finalizer is called here}
Sometimes it is infeasible for the system to be told towaitToFinalize
- for example: when the composite API is called. To make sure our finalizers can safely handle these scenarios, be sure to guard your finalizers against multiple invocations in one transaction by clearing out any collections of records you need to process:
publicvoidexecute(FinalizerHandler.Contextcontext) {if (!toProcess.isEmpty()) {this.currentlyProcessing =toProcess;System.enqueueJob(this);toProcess.clear(); }}
About
A framework for partitioning, ordering, and bypassing trigger logic for applications built on Salesforce.
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Contributors7
Uh oh!
There was an error while loading.Please reload this page.