
Force.com Cookbook Sample Code
Chapter 4: Best Practices for Writing Apex - Controlling Recursive Triggers
To download all the code samples, access the Cookbook. -
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.
trigger AutoCreateFollowUpTasks on Task (before insert) {
// Before cloning and inserting the follow-up tasks,
// make sure the current trigger context isn't operating
// on a set of cloned follow-up tasks.
if (!FollowUpTaskHelper.hasAlreadyCreatedFollowUpTasks()) {
List<Task> followUpTasks = new List<Task>();
for (Task t : Trigger.new) {
if (t.Create_Follow_Up_Task__c) {
// False indicates that the ID should NOT
// be preserved
Task followUpTask = t.clone(false);
System.assertEquals(null, followUpTask.id);
followUpTask.subject = FollowUpTaskHelper.
getFollowUpSubject(followUpTask.subject);
if (followUpTask.ActivityDate != null) {
followUpTask.ActivityDate = followUpTask.ActivityDate + 1; //The day after
}
followUpTasks.add(followUpTask);
}
}
FollowUpTaskHelper.setAlreadyCreatedFollowUpTasks();
insert followUpTasks;
}
}
Sample code provided by salesforce.com. All rights reserved.