You need to sign in to do that
Don't have an account?
Trigger on Account
Hi All,
I have created one trigger on account when criteria meet (ownership ='Public') trigger will fire and it will create a Task under the account where my code is-
trigger TaskTrigger on Account (after insert, after update) {
list<Task> lNewTasks = new list<Task>();
for(Account acc : Trigger.new){
if(acc.Ownership == 'Public'){
Task MyTask = new Task(Subject = 'My new task',
WhoID = acc.id,Status ='Completed');
system.debug('MyTask'+MyTask);
}insert lNewTasks;
}
}
Please help it where I am going wrong because it not working
Thanks In advance
MyTask is the task you're trying to create for an account, while lNewTasks should be an array of those tasks, which you would insert at the end of your loop. So, first of all, you're not inserting MyTask into the list of lNewTasks. You also have a bug if two or more accounts were modified or created at once, because lNewTasks is inside the for-loop, and so your code would try to duplicate the newly inserted tasks.
Here's all you need to do to change your code:
Instead of using a temporary task variable, just add the new entry directly into the list; the debug statement is for illustrative purposes only. Also note that a new task is created each time there is an edit, not just the first time the account ownership is marked public.
All Answers
MyTask is the task you're trying to create for an account, while lNewTasks should be an array of those tasks, which you would insert at the end of your loop. So, first of all, you're not inserting MyTask into the list of lNewTasks. You also have a bug if two or more accounts were modified or created at once, because lNewTasks is inside the for-loop, and so your code would try to duplicate the newly inserted tasks.
Here's all you need to do to change your code:
Instead of using a temporary task variable, just add the new entry directly into the list; the debug statement is for illustrative purposes only. Also note that a new task is created each time there is an edit, not just the first time the account ownership is marked public.
Hi ,
Try this
trigger TaskTrigger on Account (after insert, after update) {
list<Task> lNewTasks = new list<Task>();
list<account> acclIst = new list<account>();
for(Account acc : Trigger.new){
acclIst.add(acc);
}
for(Account acc : acclIst){
system.debug('-----acc--------'+acc.Ownership);
if(acc.Ownership == 'Public'){
Task MyTask = new Task(Subject = 'My new task',
whatid = acc.id,Status ='Completed');
lNewTasks.add(MyTask);
system.debug('MyTask'+MyTask);
}
}
insert lNewTasks;
}