FollowUpTaskHelper.apex

Image:cookbook.jpg

Force.com Cookbook Sample Code
Chapter 4: Best Practices for Writing Apex - Controlling Recursive Triggers

To download all the code samples, access the Cookbook. - Image:Key_icon.gif

This Apex trigger is part of an example that shows how to control trigger recursion by using static member variables.

For this example to work properly, you first must define a custom checkbox field on Task. In this example, this field is named Create_Follow_Up_Task__c.

public class FollowUpTaskHelper {

	// Static variables are local to the context of a Web request
	// (or testMethod during a runTests call)
	// Therefore, this variable will be initialized as false
	// at the beginning of each Web request which accesses it.

	private static boolean alreadyCreatedTasks = false;

	public static boolean hasAlreadyCreatedFollowUpTasks() {
		return alreadyCreatedTasks;
	}

	// By setting the variable to true, it maintains this
	// new value throughout the duration of the request
	// (or testMethod)

	public static void setAlreadyCreatedFollowUpTasks() {
		alreadyCreatedTasks = true;
	}

	public static String getFollowUpSubject(String subject) {
		return 'Follow Up: ' + subject;
	}
}

Sample code provided by salesforce.com. All rights reserved.