+ Start a Discussion
Andrew Aldis 15Andrew Aldis 15 

Bulkify trigger with trigger handler

I need to bulkify a trigger which utilizes a trigger handler, and am not sure how to actually call the trigger handler while using a if statement, I only need to call the trigger handler on the records that meet a specific criteria but do not know how to do it with out a for loop and calling the trigger handler multiple times.  Can someone give help me out?  My code is below.

  for(task t: trigger.new){
                  system.debug('after trigger fired');
                  if(t.status == 'Completed' && t.Primary_Campaign__c != Null && t.Primary_Campaign__r.Actionable__c == true){
                    taskTriggerHandler.updateActionableLeads(Trigger.new);
                  }
                  if(t.Follow_Up_Id__c != Null){
                    taskTriggerHandler.followUPTaskUpdate(Trigger.new);
                 }
               }
tonante27tonante27
Can you use a List ?  WIth a List you can store the task into a list of tasks and then pass a;; pf the tasks into the trigger handler having type of List<Task> SO:
Create a List of Tasks: In your case two: a) One for updateActionableLeads method b) followUPTaskUpdate
  • Load the task into the list of tasks instead of calling the handlers until the loop has finished runnning.
  • when the for loop has completed then call the trigger handler using the List of tasks  as parameters instead of Trigger.New
I thinkthat should help.
tonante27tonante27
This is what I meant if I understood you question correctly:

List<Task>  actionableLeads = new List<task>();
List<Task> followUP = new List<task>();
 for(task t: trigger.new){
                  system.debug('after trigger fired');
                  if(t.status == 'Completed' && t.Primary_Campaign__c != Null && t.Primary_Campaign__r.Actionable__c == true){
                    actionableLeads.add(t);
                  }
                  if(t.Follow_Up_Id__c != Null){
                    followUP.add(t);
                 }
               }
if(actionableLeads.size() > 0){
  taskTriggerHandler.updateActionableLeads(actionableLeads );
}

if(followUP.size() > 0){
   taskTriggerHandler.followUPTaskUpdate(followUP);
}

This is one method of bulkification - use collections like Lists, Sets, and even Maps.
tonante27tonante27
Note: You will also have to bulkify how you handle the task lists in your static methods for actionableLeads  and followUP.