Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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

2 Answers 2

up vote 3 down vote accepted

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

Trigger:

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

    ObjectTriggerHandler handler = new ObjectTriggerHandler();

    if (Trigger.isBefore) {

        handler.beforeInsert(trigger.New());

    ) else if (Trigger.isAfter) {

        handler.afterInsert(trigger.New()); 
    }
}

Class:

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
            doStuff();
        }
    }
    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
            doStuff();
        }
    }
}

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

 
discard

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.