• Stars
    star
    932
  • Rank 49,020 (Top 1.0 %)
  • Language Apex
  • License
    MIT License
  • Created over 11 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A minimal trigger framework for your Salesforce Apex Triggers

SFDC trigger framework

npm version Maintainability

I know, I know...another trigger framework. Bear with me. ;)

Overview

Triggers should (IMO) be logicless. Putting logic into your triggers creates un-testable, difficult-to-maintain code. It's widely accepted that a best-practice is to move trigger logic into a handler class.

This trigger framework bundles a single TriggerHandler base class that you can inherit from in all of your trigger handlers. The base class includes context-specific methods that are automatically called when a trigger is executed.

The base class also provides a secondary role as a supervisor for Trigger execution. It acts like a watchdog, monitoring trigger activity and providing an api for controlling certain aspects of execution and control flow.

But the most important part of this framework is that it's minimal and simple to use.

Deploy to SFDX Scratch Org: Deploy

Deploy to Salesforce Org: Deploy

Usage

To create a trigger handler, you simply need to create a class that inherits from TriggerHandler.cls. Here is an example for creating an Opportunity trigger handler.

public class OpportunityTriggerHandler extends TriggerHandler {

In your trigger handler, to add logic to any of the trigger contexts, you only need to override them in your trigger handler. Here is how we would add logic to a beforeUpdate trigger.

public class OpportunityTriggerHandler extends TriggerHandler {
  
  public override void beforeUpdate() {
    for(Opportunity o : (List<Opportunity>) Trigger.new) {
      // do something
    }
  }

  // add overrides for other contexts

}

Note: When referencing the Trigger statics within a class, SObjects are returned versus SObject subclasses like Opportunity, Account, etc. This means that you must cast when you reference them in your trigger handler. You could do this in your constructor if you wanted.

public class OpportunityTriggerHandler extends TriggerHandler {

  private Map<Id, Opportunity> newOppMap;

  public OpportunityTriggerHandler() {
    this.newOppMap = (Map<Id, Opportunity>) Trigger.newMap;
  }
  
  public override void afterUpdate() {
    //
  }

}

To use the trigger handler, you only need to construct an instance of your trigger handler within the trigger handler itself and call the run() method. Here is an example of the Opportunity trigger.

trigger OpportunityTrigger on Opportunity (before insert, before update) {
  new OpportunityTriggerHandler().run();
}

Cool Stuff

Max Loop Count

To prevent recursion, you can set a max loop count for Trigger Handler. If this max is exceeded, and exception will be thrown. A great use case is when you want to ensure that your trigger runs once and only once within a single execution. Example:

public class OpportunityTriggerHandler extends TriggerHandler {

  public OpportunityTriggerHandler() {
    this.setMaxLoopCount(1);
  }
  
  public override void afterUpdate() {
    List<Opportunity> opps = [SELECT Id FROM Opportunity WHERE Id IN :Trigger.newMap.keySet()];
    update opps; // this will throw after this update
  }

}

Bypass API

What if you want to tell other trigger handlers to halt execution? That's easy with the bypass api:

public class OpportunityTriggerHandler extends TriggerHandler {
  
  public override void afterUpdate() {
    List<Opportunity> opps = [SELECT Id, AccountId FROM Opportunity WHERE Id IN :Trigger.newMap.keySet()];
    
    Account acc = [SELECT Id, Name FROM Account WHERE Id = :opps.get(0).AccountId];

    TriggerHandler.bypass('AccountTriggerHandler');

    acc.Name = 'No Trigger';
    update acc; // won't invoke the AccountTriggerHandler

    TriggerHandler.clearBypass('AccountTriggerHandler');

    acc.Name = 'With Trigger';
    update acc; // will invoke the AccountTriggerHandler

  }

}

If you need to check if a handler is bypassed, use the isBypassed method:

if (TriggerHandler.isBypassed('AccountTriggerHandler')) {
  // ... do something if the Account trigger handler is bypassed!
}

If you want to clear all bypasses for the transaction, simple use the clearAllBypasses method, as in:

// ... done with bypasses!

TriggerHandler.clearAllBypasses();

// ... now handlers won't be ignored!

Overridable Methods

Here are all of the methods that you can override. All of the context possibilities are supported.

  • beforeInsert()
  • beforeUpdate()
  • beforeDelete()
  • afterInsert()
  • afterUpdate()
  • afterDelete()
  • afterUndelete()

More Repositories

1

nforce

nforce is a node.js salesforce REST API wrapper for force.com, database.com, and salesforce.com
JavaScript
474
star
2

dmc

The file-system-like, cross-platform, cli developer tool for Salesforce
JavaScript
69
star
3

Force.com-Helper-Classes

A collection of useful helper classes for Salesforce and Force.com.
Apex
61
star
4

grunt-ant-sfdc

Add salesforce and force.com ANT tasks to your grunt builds
JavaScript
57
star
5

salesforcedx-circleci-demo

A demo project showing a Salesforce project being built with SalesforceDX and Circle CI
Shell
31
star
6

elkington

A node.js module for interfacing with the Elk M1 Gold automation controller
JavaScript
22
star
7

premote

wrap javascript remote actions in a promise api
JavaScript
20
star
8

nforce-metadata

An nforce plugin that facilitates working with the Salesforce metadata api
JavaScript
19
star
9

sfdc-developer-tools

A helpful list of developer tools for Salesforce
10
star
10

nforce-express

express.js plugin for nforce
JavaScript
7
star
11

sfdc-pkg-postinstall

A postinstall script to make salesforce metadata able to be installed with npm
JavaScript
6
star
12

react-df14

React.js demo for DF14
JavaScript
5
star
13

DF11BatchItUpDemo

This is the source code from our demo at Dreamforce '11 on Batch Apex
5
star
14

cluster-bomb

a node.js cluster management and monitoring system for explosive results
JavaScript
4
star
15

meetup-twitter-bot

A node.js app for automatically following your meetup.com group users from your twitter account
JavaScript
4
star
16

realtime-df12

Repo for the Dreamforce 2012 presentation, Realtime Apps with node.js, heroku, and Force.com Streaming API.
JavaScript
3
star
17

shef

A node.js client for your DIRECTV boxes.
JavaScript
3
star
18

connect-leveldb

a connect session store implementation for leveldb
JavaScript
3
star
19

express-gateway-chart

A helm chart for deploying express-gateway to kubernetes
Smarty
3
star
20

GitHub-for-Salesforce

An integration between GitHub and Salesforce
2
star
21

socketio-hover-demo

A demo showing how you can easily use socket.io to stream DOM events to a node.js app
JavaScript
2
star
22

apex-bug

Community-driven Apex issue submission
2
star
23

kobe

a node and express-based blogging engine
2
star
24

jquery-selectbind

Create dependent select lists.
JavaScript
2
star
25

sfdc-einstein-meetup

Code from the Salesforce Einstein meetup preso
Apex
2
star
26

ayah-sfdc

are you a human for Salesforce.com
1
star
27

node-dnsimple-updater

a dnsimple updater
JavaScript
1
star
28

staque

build multiple, on-the-fly synchronous job queues
JavaScript
1
star
29

configa

app configuration management for node.js
JavaScript
1
star
30

aki

aki is an anti-spam module for node.js that works with the akismet API
1
star