Created
December 15, 2011 15:42
-
-
Save pcon/1481545 to your computer and use it in GitHub Desktop.
Classifying triggers in Salesforce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trigger MyObject on MyObject__c (before insert, before update, before delete, after insert, after update, after delete) { | |
MyObjectTrigger.processTrigger(Trigger.oldMap, Trigger.new, Trigger.isBefore); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyObjectTrigger { | |
private final Map<Id, MyObject__c> oldMap; | |
private final Map<Id, MyObject__c> newMap; | |
private final List<MyObject__c> newObjs; | |
private final Boolean isInsert; | |
private final Boolean isUpdate; | |
private final Boolean isDelete; | |
private final Boolean isBulk; | |
/** | |
* The constructor | |
* | |
* @param xoldMap The old map from the trigger | |
* @param xnewObj The list of new objects from the trigger | |
* @param isBefore If the trigger is in before or after | |
*/ | |
public MyObjectTrigger(Map<Id, MyObject__c> xoldMap, List<MyObject__c> xnewObjs, Boolean isBefore) { | |
oldMap = xoldMap; | |
newObjs = xnewObjs; | |
if (!isBefore && newObjs != null) { | |
newMap = new Map<Id, MyObject__c>(newObjs); | |
} | |
isDelete = (((newObjs == null || newObjs.isEmpty()) && isBefore) || ((newMap == null || newMap.isEmpty()) && !isBefore)); | |
isUpdate = ! (isDelete || oldMap == null || oldMap.isEmpty()); | |
isInsert = ! (isDelete || isUpdate); | |
isBulk = (newObjs != null && newObjs.size() > 1) ? true : false; | |
} | |
public void doAwesomeness() { | |
//Do stuff | |
} | |
/** | |
* Method to initiate trigger logic | |
* | |
* @param oldMap The old map from the trigger | |
* @param newObj The list of new objects from the trigger | |
* @param isBefore If the trigger is in before or after | |
*/ | |
public static void processTrigger(Map<Id, MyObject__c> oldMap, List<MyObject__c> newObj, Boolean isBefore) { | |
final MyObjectTrigger myTrigger = new MyObjectTrigger(oldMap, newObj, isBefore); | |
if (isBefore) { | |
myTrigger.doAwesomeness(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment