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
Manjunath reddy 6Manjunath reddy 6 

Create an Apex trigger for Opportunity that adds a task to any opportunity set to 'Closed Won'.

trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {
List<task> carry=New List<task>();

  for(opportunity opp:trigger.new){
   if(opp.stagename=='closed own'){
    task t=new task(whatid=opp.id);
    carry.add(t); 
    }
   }
     insert carry;

 }

 The trigger will add a task to any opportunity inserted or updated with the stage of 'Closed Won'. The task's subject must be 'Follow Up Test Task'.The Apex trigger must be called 'ClosedOpportunityTrigger'
With 'ClosedOpportunityTrigger' active, if an opportunity is inserted or updated with a stage of 'Closed Won', it will have a task created with the subject 'Follow Up Test Task'.
To associate the task with the opportunity, fill the 'WhatId' field with the opportunity ID.
This challenge specifically tests 200 records in one operation.

I tried with the above code, task is not created.
Best Answer chosen by Manjunath reddy 6
Subodh shuklaSubodh shukla
there is spelling mistake bro it should be 'Closed Won' instead of 'closed own'

All Answers

Alexander TsitsuraAlexander Tsitsura
Hi Manjunath,

Additionaly u need populate subject field in task record as "Follow Up Test Task"

Try this code
trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {
List<task> carry=New List<task>();

  for(opportunity opp:trigger.new){
   if(opp.stagename=='Closed Own'){
    task t=new task(
        whatid=opp.id, 
        Status = 'Active',
        Subject = 'Follow Up Test Task',
        ActivityDate = system.today()
     );
    carry.add(t); 
    }
   }
     insert carry;

 }
As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you.

Thanks,
Alex
 
Subodh shuklaSubodh shukla
there is spelling mistake bro it should be 'Closed Won' instead of 'closed own'
This was selected as the best answer
☯ BonY ☯☯ BonY ☯
Hi,

Try this below code
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update)
{ 
    List<Task> tasks = new List<Task>(); 
    for (Opportunity Opp : Trigger.new) 
    { 
        if(Opp.StageName == 'Closed Won')
        {
        Task tsk = new Task(whatID = Opp.ID, subject='Follow Up Test Task'); 
        tasks.add(tsk); 
        }
    } 
    insert tasks; 
}

 
Manjunath reddy 6Manjunath reddy 6
Subodh thanks for finding the mistake,my code was not working because of spelling mistake.
Abhinav SinghAbhinav Singh
Try this code
 
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
 	List<Task> tasks = new List<Task>();
    for(Opportunity op : [Select Id from Opportunity where Id in :Trigger.New AND StageName='Closed Won'])
    {
        Task task = new Task(WhatId = op.Id, Subject = 'Follow Up Test Task');
        tasks.add(task);
    }
    insert tasks;
}

 
Lucas Duque 9Lucas Duque 9
I noticed the answers and  realize that had no solution like mine, however, very similar.

Follows my way to solve this challenge:
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {

    List<Task> taskList = new List<Task>();
    
    FOR (Opportunity opp: [SELECT Id, StageName FROM Opportunity WHERE StageName = 'Closed Won']) 
    {
        task taskvalues = new task (WhatId = opp.Id, Subject = 'Follow Up Test Task');
        
        taskList.add(taskvalues);
    }
    
    //if variable taskList is greater than 0, insert operation.
    if (taskList.size () > 0 ) {
        insert taskList;
    }
}



 
Chitranjan Chetkar 3Chitranjan Chetkar 3
Bulk Design Pattern in Action: Trigger solution
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
List<Task> taskList = new List<Task>(); // for new record
    for(Opportunity o : [SELECT Id, StageName from Opportunity 
                         WHERE Id IN : Trigger.New AND StageName = 'Closed Won'] ) {
                               taskList.add(new Task (Subject = 'Follow Up Test Task', WhatId = o.Id));            
    }
    insert taskList;
}

 
Vitaliy UrusovskijVitaliy Urusovskij
Try this code. When I submit, it was a success:

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    List <Task> opptask = new List<Task>();
    
    List<Opportunity> opp = [SELECT Id FROM Opportunity WHERE Id in :Trigger.New AND StageName = 'Closed Won'];
    
    for (integer i = 0; i < opp.size(); i++)
    {
        task t = new task(WhatId = opp.Id, subject = 'Follow Up Test Task');
        opptask.add(t);
    }
    if (opptask.size() > 0)
        insert opptask;
}
Dan GillhamDan Gillham
I am having a little bit different problem with this challenge in the respect that the console is not recognizing my variables and stating that they do not exist. I have tried the above code and other people's code that have successfully passed to no avail. Can you look at the following screenshot and tell me what is wrong?
ClosedOppTrig snapshot
Is this something amiss in the system since the fields are in the Opportunities object or do I have a syntax issue?
 
kanakaraju mkanakaraju m
Challenge not yet complete... here's what's wrong:
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Discount_Percent__c]: [Discount_Percent__c]

am facing this error with the below code, Can anyone look into the code and tell me whats wrong?
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {

    List<Task> tList = new List<Task>();
    
    FOR (Opportunity opp: [SELECT Id, StageName FROM Opportunity WHERE StageName = 'Closed Won']) 
    {
        task values = new task (WhatId = opp.Id, Subject = 'Follow Up Test Task');
        
        tList.add(values);
    }
    
   
    if (tList.size () > 0 ) {
        insert tList;
    }
}
qun chenqun chen
just set 'Discount_Percent__c' field as not required in opportunity object.
SAI LAKSHMAN KATTOJUSAI LAKSHMAN KATTOJU

Challenge not yet complete in My Trailhead Playground 1
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, We can't save this record because the “Opportunity Management” process failed. Give your Salesforce admin these details. This error occurred when the flow tried to create records: REQUIRED_FIELD_MISSING: Required fields are missing: [AccountId]. You can look up ExceptionCode values in the SOAP API Developer Guide. Error ID: 377956270-241564 (-667225970): []

 

 

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {

    List<Task> taskListToInsert = new List<Task>();
    
    for(Opportunity opp:Trigger.new)
    {
        if(opp.StageName == 'Closed Won')
        {
            Task t = new Task();
            t.Subject = 'Follow Up Test Task';
            t.WhatId = opp.Id;
            taskListToInsert.add(t);
        }
    }
    
    if(taskListToInsert.size() > 0)
    	{
        	insert taskListToInsert;
    	}
}

I'm getting this error continuously can someone help me out, please
 
Celio XavierCelio Xavier
Segue a minha solução: 
 
trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {
List<task> carry=New List<task>();
  	for(opportunity add:trigger.new){
   		if(add.stagename=='Closed Won'){
    	task t=new task(
        whatid=add.id, 
        Status = 'Active',
        Subject = 'Follow Up Test Task',
        ActivityDate = system.today()
     	);
    	carry.add(t); 
    	}
   }
     insert carry;
 }

 
Siemel Naran 11Siemel Naran 11
While the question doesn't ask, it might be good to not create the task if it already exists.  Here's what I came up , though not sure if it could be improved.
 
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    String DEFAULT_SUBJECT = 'Follow Up Test Task';
    Set<Id> existingTasks = new Set<Id>();
    if (Trigger.isUpdate) {
        List<Task> taskList = [SELECT WhatId FROM Task WHERE WhatId IN :Trigger.Old AND Subject = :DEFAULT_SUBJECT];
        for (Task task : taskList) {
            existingTasks.add(task.WhatId);
        }
    }
    List<Task> newTasks = new List<Task>();
    for (Opportunity opportunity : Trigger.New) {
        if (opportunity.StageName == 'Closed Won') {
            if (!existingTasks.contains(opportunity.Id)) {
            	Task task = new Task(WhatId = opportunity.Id, Subject = DEFAULT_SUBJECT);
            	newTasks.add(task);
            } else {
    			System.debug('[ClosedOpportunityTrigger] Oppportunity ' + opportunity.Id + ' already contains Task ' + DEFAULT_SUBJECT);
            }
        }
    }
    if (newTasks.size() > 0) {
        insert newTasks;
    }
}

 
yan fei 8yan fei 8
here is successful code:
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
	List<Task> tasks = new List<Task>();
    List<Opportunity> opps = [SELECT Id FROM Opportunity WHERE Id IN :Trigger.New AND StageName='Closed Won'];
    for(integer i=0;i<opps.size();i++)
    {
        task t = new Task(WhatId = opps[i].Id, Subject = 'Follow Up Test Task');
        tasks.add(t);
    }
    
    if(tasks.size() > 0)
    {
        insert tasks;
    }
    
}

 
Piyush Ganorkar 3Piyush Ganorkar 3

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update)
{
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert || Trigger.isUpdate)
        {
               List<task> tasLists = new List<task>();
            for(opportunity opp : Trigger.new)
              {    
                   if(opp.stagename =='Closed Won')
                   {
                    task tas = new task(Whatid = opp.id, Status = 'Active', Subject = 'Follow Up Test Task', 
                                           Priority = 'High', ActivityDate = system.today());
                       tasLists.add(tas); 
                }
              }
            if(tasLists.size()>0)
            {
                 insert tasLists;   
            }
        }
    }    
}
harish pandenaharish pandena
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    
  List<Opportunity> toProcess =null;
    
    switch on Trigger.operationType{
        when AFTER_INSERT{
           toProcess=Trigger.New; 
        }
        when AFTER_UPDATE{
            toProcess= [select id,StageName from Opportunity where id in:Trigger.New AND StageName='Closed Won'];        
        }
    }
    List<Task> taskList = new List<Task>();
    for(Opportunity p:toProcess){
        if(p.StageName=='closedWon'){
            Task t = new Task();
            t.WhatId=p.Id;
            t.subject='Follow Up Test Task';
            taskList.add(t);
        }
        insert taskList;
    }