Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've a variable declared at the beginning of my Trigger. Now (after the variable declaration) I've an .isBefore and an is.After contexts , and I'd like to retain variable value in both contexts, but, debugging the value at the end of .isBefore it has the expected value, losing it when .isAfter fires. (while I need its value in .isAfter)

How could I retain the variable value in every context of my trigger?

share|improve this question
up vote 5 down vote accepted

Borrowing from the most common trigger pattern, I think you'll need to use a helper class to achieve this.


trigger ObjectTrigger on Object (before insert, after insert) {

    ObjectTriggerHandler handler = new ObjectTriggerHandler();

    if (Trigger.isBefore) {


    ) else if (Trigger.isAfter) {



public with sharing class ObjectTriggerHandler() {

    private static Boolean isBefore = false;
    private static Boolean isAfter = false;

    public void beforeInsert (List<Object> newList) {

        // Before insert logic goes here, check isBefore for recursion protection
        if (!isBefore) {

            // Set flag to true to prevent recursion
            isBefore = true;

            // Now perform logic
    public void afterInsert (List<Object> newList) {

        // After insert logic goes here, check isAfter for recursion protection
        if (!isAfter) {

            // Set flag to true to prevent recursion
            isAfter = true;

            // Now perform logic

Here is a great article on trigger best practices & frameworks.

share|improve this answer

A trigger is similar to a class, even allowing static variables within the trigger body. However, static variables in a trigger are reset before each call, and therefore are not truly static (the "static" effect is ignored for variables in trigger bodies).

Therefore, to retain a value across trigger events, such as before insert and after insert, you need to use a class to store that data.

The class:

public class A {
    public static String value;

The trigger:

trigger B on X (before insert) {
    if(Trigger.isBefore) {
        a.value = 'Hello World';
    } else {
        System.assertEquals('Hello World', a.value);
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.