You need to sign in to do that
Don't have an account?
Walid
Bulkify a Trigger
Hi there,
I am new to Triggrs, and trying to bulkify the below Trigger. The Trigger will create a Task when stage is Closed Won. It will also check if the Opportunity already has a Task with the same Subject, and it won't create the tasks in this case.
The Trigger is:
Thanks.
Walid
I am new to Triggrs, and trying to bulkify the below Trigger. The Trigger will create a Task when stage is Closed Won. It will also check if the Opportunity already has a Task with the same Subject, and it won't create the tasks in this case.
The Trigger is:
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) { //create a list of tasks to be added List<Task> listTasks = new List<Task>(); for (Opportunity opp : Trigger.New){ //create a list of Tasks already created with same subject on opp List<Task> existingTasks = [SELECT Id FROM Task WHERE WhatId = :opp.Id AND Subject = 'Follow Up Test Task']; //add new task only if stage is Closed Won and no existing task with same subject on opp if ((opp.StageName == 'Closed Won') && (existingTasks.size() == 0) ){ Task newTask = new Task(); newTask.WhatId = opp.Id; newTask.Subject = 'Follow Up Test Task'; newTask.Status = 'Not started'; newTask.OwnerId = opp.OwnerId; listTasks.add(newTask); } } insert listTasks; }I want to move the SOQL query our of the For loop, but if I do it, it will look for Tasks with this subject throughout the whole Trigger.New opportunity list. How can I move it out and keep count of each opportunity having this task with this subject?
Thanks.
Walid
Try the below it will work for bulk load.
Thanks,
Vijay
1- Line 11 (Id oppId=tsk.whatId;): tsk.whatId should be added in the SOQL right? So, the SOQL would become: SELECT Id, whatId... ?
2- Line 12 (List<Task> oppTasks=tasksByOppId.get(oppId);): Isn't tasksByOppId still empty atthis stage? What will asksByOppId.get(oppId); return?
3- Line 18: what did you add? oppTasks.add(task);
Regards,
Walid
This is what I was doing, but in your code, existingTasks will search for these tasks across ALL opportunities. and the task will not be added unless ALL opportunities don't have such task. So in other words, if Trigger.New is 10 opportunities, and 1 of them has this task, none of these 10 will have a task added.
I guess a map is the way to go.
Please try below code.
Let us know if this will help you