function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Base Line 7Base Line 7 

How to pass trigger instance to handler class?

Hi. I want to code for a trigger in Apex but I want the logic to reside in a handler class and have only one statement in the trigger itself which references a static method in the handler class. Basically something like this:

trigger myTrigger on sObject (after update, after insert, after delete, after undelete){
HandlerClass.executeTriggerLogic(args[]);
}

public class HandlerClass{
public static void executeTriggerLogic (args[])
{
//trigger logic
{

//other methods...
}

Is this possible and what would I need to pass from the trigger to the Handler as the args[] to make this work? Any help would be much appreciated. Thanks.
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Base Line 7

      You need to pass correct Trigger context variables associated with each of your trigger events. In your case you should use the following
 
trigger myTrigger on SObject (after update, after insert, after delete, after undelete){

       HandlerClass handler = new HandlerClass();

       if(Trigger.isUpdate && Trigger.IsAfter){
 
              // with after update trigger event you can use two context variables Trigger.new &
             //  Trigger.oldMap. Trigger.oldMap will have values before update operation.
              handler.onAfterUpdateProcess (Trigger.new, Trigger.oldMap);
       }

       if(Trigger.isInsert && Trigger.IsAfter){
 
              // with after insert trigger event you can only use Trigger.new
              handler.onAfterInsertProcess (Trigger.new);
       }

       if(Trigger.isDelete && Trigger.IsAfter){
 
              // with after delete trigger event you can use Trigger.oldMap
              handler.onAfterDeleteProcess (Trigger.oldMap);
       }

      if(Trigger.isUnDelete && Trigger.IsAfter){
 
              // with after delete trigger event you can use Trigger.oldMap
              handler.onAfterUnDeleteProcess (Trigger.oldMap);
       }
}
For your reference
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables.htm

I hope the above answer is helpful for you. 

Regards
Karthikeyan