1

Apex trigger can be declared with below code:

Trigger AccountTrigger on Account (before insert){
      static count=0;
}

Does the statements means the trigger cannot contain static blocks Eg;

Trigger AccountTrigger on Account(before insert){
       Static{
           //code goes here
       }
}
1
  • 1
    This is a very easy thing to test. What happens when you try? Jul 17, 2018 at 13:11

2 Answers 2

4

That's correct. You can declare and use static variables in a trigger, but you cannot use static initializer blocks. See Static and Instance Methods, Variables, and Initialization Code, which notes another critical caveat about declaring statics within the body of a trigger:

A static variable defined in a trigger doesn’t retain its value between different trigger contexts within the same transaction, such as between before insert and after insert invocations. Instead, define the static variables in a class so that the trigger can access these class member variables and check their static values.

Although it's legal to declare statics in a trigger body, generally, it's better to place these statics in a trigger handler class. You're also able to use static initializer blocks in that context.

0

Body of a Trigger can have a Static Keyword. However, in each trigger execution context, Value of the Static Variable won't be retained. If you want the values of the Static Value to be retained ( as we do to avoid recursive trigger calls), put the static variable in the class. Check this- Static variables defined in a trigger

You must log in to answer this question.

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