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
Staci CaraStaci Cara 

Constructor in AfterTrigger

Hi guys, 

I am having this trigger Handler and I want to use a Constructor, which is calling a class that has methods I need to use. 

My problem is that I want to initialize the constructor in the beforeTrigger Method and call a method of the class in the afterTrigger part. 

Means something like this:

public with sharing class SObjectTriggerHandler extends TriggerHandler {
    Class class;

    public override void beforeUpdate() {
           class = new Class((List<SObject>) Trigger.new, (Map<Id,SObject>) Trigger.oldMap);
    }
   

    public override void afterUpdate() {
          if(class != null) {

class.method();

}

    }

But the afterTrigger won't call the method, because class is null. 

I guess it has to do with the notation at the beginning, since I am initializing the constructor in the beforeTrigger, but isn't that so that the beforeTriggers get executed before the AfterTriggers? Shouldn't then the class have a value. 

After the beforeUpdate the class has defently a value and isn't null. 

What am I doing wrong? Could please somebody help me with this issue? It is urgent!

Thank you in advance! 

RD@SFRD@SF
Hi Staci,

I think its cause the class is out of the scope. Before trigger and the After trigger running on different scopes. You can solve this by using the following pseudo code
 
trigger on <object>( after event, before event)
{
//declare the class you want to use here
NeededClass a = new NeededClass();

//the call the trigger helper class from here
if(Trigger.IsEvent)
{
        TriggerHelperclass.EventFunction(,a);//pls note how I am passing the Needed class tot the trigger class along with the EventFunction which can be after update, before update.
}
 
}

//you might have to update the trigger helper class to accept the needed class as a parameter.

// this way your scope would be the same, and should fix your issue.
//Also, handle recursion carefully here

Hope it helps
RD
Staci CaraStaci Cara

Hey RD, 

would I need to write a new constructor for the class? Right now I just have the constructor that takes parameters.

And the comma is on purpose? What does this notatio mean actually? I tried it your way, but it doesn't want to work. :(