function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
carlsosgcarlsosg 

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.

Best Answer chosen by Admin (Salesforce Developers) 
Ritesh AswaneyRitesh Aswaney

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

Ritesh AswaneyRitesh Aswaney

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);

 

}

carlsosgcarlsosg

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?

Ritesh AswaneyRitesh Aswaney

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));

 

}

This was selected as the best answer