+ Start a Discussion
Rabbani sayyed 8Rabbani sayyed 8 

I need to Create an Apex trigger for Opportunity that adds a task to any opportunity set to 'Closed Won' . Can anyone share me the code for this with best practises.

I need to Create an Apex trigger for Opportunity that adds a task to any opportunity set to 'Closed Won' . Can anyone share me the code for this with best practises.
Dutta SouravDutta Sourav
Hi Rabbani,

You can achieve this easily through Workflow (Task).

However, With Trigger  You can use this code:
trigger OpportunityTask on Opportunity (before insert,before update){
 for( Opportunity opp:Trigger.new)
    {
        if(opp.StageName=='Closed Won')
        {
           task t=new task();
           t.whatid=opp.id;   
           t.subject='New Task' ; // You can put your own subject.
               insert t; 
    }

    }
}

Warm Regards,
Sourav.
Head In CloudHead In Cloud
Hi Rabbani,

You can use this code:

trigger testTrigger on Opportunity(before update, after insert){
 list<task> listToInsert = new list<task>();
 for(opportunity opp : trigger.new){
  if(opp.stageName == 'Closed Won'){
   task taskObject = new task();
   taskObject.whatId = opp.Id;
   taskObject.subject = 'test';
   listToInsert.add(taskObject);
  }
 }
 if(!listToInsert.isEmpty()){
  insert listToInsert;
 }
}


Hope this helps!
​Thanks

 
Arun KumarArun Kumar
Hi,

You must go with Workflow Only. But also if you want trigger then pls refer below code:
trigger OpportunityTask on Opportunity (before insert,before update){
List<Task> taskInsertList = new List<Task>();
 for( Opportunity opp:Trigger.new)
    {
        if(opp.StageName=='Closed Won' && (Trigger.isInsert || (Trigger.isUpdate && Trigger.OldMap != null && Trigger.oldMap.get(opp.Id).StageName != opp.StageName)))
    {
           task t=new task();
           t.whatid=opp.id;   
           t.subject='New Task' ; // You can put your own subject.
           taskInsertList.add(t); 
    }

if(!taskInsertList .isEmpty()) insert taskInsertList ;

    }
}