You need to sign in to do that
Don't have an account?

APEX Trigger to create an Account Task when Opportunity StageName Changes
I am trying to figure out the best way to do this with APEX, but how can I create an Account Task when an Opportunity StageName value is changed to "Closed Won"?
I want to be able to assign the task to the Account Owner and the Account Owner Manager.
You would just need another line inside the for loop to create a new task and assign it to the 'Account Owner Manager'
for (Account acc : [Select Id, Name, OwnerId from Account where Id IN :accountIds]){
tasksToInsert.add(new Task(WhatId=acc.Id, OwnerId=acc.OwnerId));
tasksToInsert.add(new Task(WhatId=acc.Id, OwnerId=acc.THE OWNER FIELD YOU WANT TO REFERENCE));
}
All Answers
trigger OpportunityAfter on Opportunity (after update){
Id[] accountIds = new Id[]{};
for(Opportunity opp : trigger.new)
if(opp.StageName == 'Closed Won' && trigger.oldMap.get(opp.Id).StageName != opp.StageName)
accountsIds.add(opp.AccountID);
Task[] tasksToInsert = new Task[]{};
for (Account acc : [Select Id, Name, OwnerId from Account where Id IN :accountIds])
tasksToInsert.add(new Task(WhatId=acc.Id, OwnerId=acc.OwnerId));
if(tasksToInsert != null && !tasksToInsert.isEmpty())
Database.insert(tasksToInsert);
}
Thank you - that definitely points me in the right direction.
Now, how can I create 2 tasks at the same time - one for the Account Owner (as you demonstrated), and one for the Account Owner's Manager?
You would just need another line inside the for loop to create a new task and assign it to the 'Account Owner Manager'
for (Account acc : [Select Id, Name, OwnerId from Account where Id IN :accountIds]){
tasksToInsert.add(new Task(WhatId=acc.Id, OwnerId=acc.OwnerId));
tasksToInsert.add(new Task(WhatId=acc.Id, OwnerId=acc.THE OWNER FIELD YOU WANT TO REFERENCE));
}