0

I want to create a trigger that will only pass its trigger context to a static method in a handler class I have created where all the business logic resides. I want to pass the trigger context directly to my handler as shown in the case below but it seems that it is not possible to reference the trigger context outside of a trigger.

//For the trigger

trigger myTrigger on sObject (after insert, after update, after delete, after undelete){

     TriggerHandler.applyLogic(Trigger);

}

//For the handler

public class TriggerHandler{
     public static void(Trigger){

     //Business Logic

     }

     //Other methods, etc... 
}

It is for this reason that it seems I have to create a wrapper class that can be used to strip down the variables and pass them into my handler. Question is - how do I create such a wrapper class? I would like to include all the Trigger Context Variables including the operationType variable in the wrapper. Any help would be greatly appreciated. Many thanks in advance.

1 Answer 1

1

You can access trigger methods in a class:

public class TriggerHandler {
  public static void applyLogic() {
    switch on (Trigger.operationType) {
      when BEFORE_INSERT {
        // logic here //
      }
    }
  }
}

Or, you can use the design pattern from the blog post that introduced switches:

BrokerTriggerHandler.handleTrigger(Trigger.new, Trigger.old, Trigger.operationType);

...

public static void handleTrigger(List<Broker__C> workingRecords, List<Broker__c> oldRecords, System.TriggerOperation triggerEvent ) {
  // ... //

You could write a wrapper class if you really wanted to, but there's really only three variables you really need to worry about (those listed above).

2
  • Thanks for the reply sfdcfox. The ability to access trigger methods in a class is certainly a useful piece of information to know. How does the handler work on the current trigger context without referencing it explicitly? And is it also possible to execute commands from the handler class like looping through old, and accessing the fields in the sObject on which the trigger is set as well?
    – user71712
    Commented Aug 8, 2019 at 2:59
  • 1
    @user71712 Using parameters is the typical method (as in the second example). You can access Trigger.new/Trigger.old explicitly, but outside of a trigger, they are SObject[] arrays, meaning you have to "cast" them to an explicit type (e.g. Account[] old = (Account[])Trigger.old;).
    – sfdcfox
    Commented Aug 8, 2019 at 3:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .