Apex Trigger Actions Framework

Apex Trigger Actions Framework

Many Salesforce developers have abstracted the trigger away from its implementation and allowed us to author trigger handler classes which look like this:

public class OpportunityTriggerHandler extends TriggerHandler { 

  public override void beforeUpdate() { 
    for(Opportunity o : (List<Opportunity>) Trigger.new) {
      //do some stuff
    }
  }

}
         

This has worked well in the past and allowed us to write one trigger per sObject, control the order of execution, prevent recursion, and reduce overall complexity. However, using the existing trigger frameworks means that as new functionality is requested, the context methods such as OpportunityTriggerHandler.beforeUpdate must be continuously modified and the OpportunityTriggerHandler class itself becomes large and difficult to work with.

I have created a new trigger framework which allows us to truly separate trigger actions from the trigger handlers and use custom metadata to control their order of execution. With this new framework, developers can author a single class to implement whatever feature functionality they desire and not have to worry about turning a handler like the OpportunityTriggerHandler into an unmaintainable monstrosity.

For example, if we had a new rule where we wanted to prevent the insertion of an Opportunity if its StageName did not equal 'Prospecting', we could build that functionality by authoring a single class like this:

public class ta_Opportunity_StageInsertRules implements TriggerAction.BeforeInsert { 

  @TestVisible
  private static final String INVALID_STAGE_INSERT_ERROR = String.format('The Stage must be {0} when an Opportunity is created', new String[] {Constants.OPPORTUNITY_STAGENAME_PROSPECTING});

  public void beforeInsert(List<Opportunity> newList) { 
    for(Opportunity opp : newList) {
      if (opp.StageName != Constants.OPPORTUNITY_STAGENAME_PROSPECTING) {
	    opp.addError(INVALID_STAGE_INSERT_ERROR);
      }
    }
  }

}

Then we can specify the sObject, context, and order in which it executes using custom metadata instead of modifying our trigger handler class. This will greatly simplify the management of your trigger code throughout time.

No alt text provided for this image

Please check out the project's repository for more information and share this post with your organization's Salesforce architects and developers.

Emilio Taylor

Sr Technical Program Manager at Amazon

4 年

This is great! Thanks for sharing Mitchell

回复
Barton Ledford

Sales & Delivery Executive, Federal Salesforce & LCNC Centers of Excellence

4 年

Have you measured how this impacts performance?

要查看或添加评论,请登录

Mitch Spano的更多文章

社区洞察

其他会员也浏览了