+ Start a Discussion
Sankhadeep  BiswasSankhadeep Biswas 

Solution of " Create an Apex trigger for Opportunity that adds a task to any opportunity set to 'Closed Won'." giving error

For the above qus I wrote the below code : 

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

List<Task> t1=new List<Task>();


for (opportunity a :[select ID,StageName  from opportunity where StageName='Closed Won' and ID IN :Trigger.New])
{


t1.add(new Task(subject= 'Follow Up Test Task', WhatId=a.ID));

if(t1.size() >0 && t1.size()<=200)
{
insert t1;
}
}
}



But getting a error like   :
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: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, trig_conts_opprty: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id 0032800000QkI6aAAF; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Trigger.trig_conts_opprty: line 10, column 1: []


Anyone please tell me the possible reason for the error ?
VamsiVamsi
Try to perform insert operation after the for loop....!!!
iliana sancheziliana sanchez
Solution of " Create an Apex trigger for Opportunity that adds a task to any opportunity set to 'Closed Won'." :

trigger ClosedOpportunityTrigger on Opportunity (before insert) {
    List<Task> listTask=new List<Task>();
    for(Opportunity o : Trigger.new){
        if(o.StageName.equals('Closed Won')){
            Task t=new Task(Subject='Follow Up Test Task', WhatId=o.Id);
            listTask.add(t);       
        }
    }
     insert listTask;
}

I wait help you.
H K 32H K 32
Just copy past below code exactly in your trailhead account and check challenge, it will be successful:

trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {
    
    List<Task> taskList=new List<Task>(); 

    for(Opportunity Opp:Trigger.New){
        if(Trigger.isInsert || Trigger.isUpdate)
          if(opp.StageName=='Closed Won')
              taskList.add(new task(Subject='Follow Up Test Task',
                                 WhatId=opp.Id));
    }
    
    if(taskList.size()>0)
        insert taskList;

}

 
asmita mehtaasmita mehta
H K 32 Your given code worked for me.
Thanks.
Ajay K DubediAjay K Dubedi
Hi Sankhadeep,

The solution of " Create an Apex trigger for Opportunity that adds a task to any opportunity set to 'Closed Won' ":
Try the following code:
 
Trigger:

trigger ClosedOpportunityTrigger on Opportunity (after isInsert,after isUpdate) {
    if(trigger.isInsert || trigger.isUpdate){
    UpdateOpportunity.checkOpportunityStage(trigger.new);
    }
}
TRIGGER HANDLER:
public class UpdateOpportunity{
    public static void checkOpportunityStage(List<Opportunity> opportunityList){
    if(opportunityList.size()>0){
		List<Task> taskList=new List<Task>();
			for(Opportunity op:opportunityList){
				if(opp.StageName=='Closed Won'){
				Task task1=new Task();
				task1.Subject='Follow Up Test Task';
				task1.WhatId=op.Id;
				taskList.add(task1);                      
		    }
		   }
		if(taskList.size()>0){
		   insert taskList;
		}
    }
}



I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi


 
Prashant RupnurPrashant Rupnur
trigger ClosedOpportunityTrigger on Opportunity (after insert , after update) {
    list<task> TaskToadd = new list<task>();
    for (Opportunity opp: trigger.new)
    {
        if (opp.StageName =='Closed Won'){
            task t = new task();
            t.whatID = opp.id; 
            t.Subject='Follow Up Test Task';
            TaskToadd.add(t);
        }
    }
    if(TaskToadd.size() > 0){
        database.insert(TaskToadd);
    }
}
Yamala  HareeshYamala Hareesh
@H K 32 your give the right code 
Thank you
Nitin Kumar SharmaNitin Kumar Sharma
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    list<task> tasksList = new list<task>();
    for(Opportunity opps : [Select Id from Opportunity where (
                                StageName='Closed Won'    AND ID IN :Trigger.new
                            )]){
        task t = new task();
        t.Subject = 'Follow Up Test Task';
        t.WhatId = opps.id;
        tasksList.add(t);
                                
    }//for loop over..
    
    if(tasksList.size()>1){
        insert tasksList;
    }
}
Elias NegasaElias Negasa
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {

    List<Opportunity> opps = new List<Opportunity>();
    List<Task> tsk = new List<Task>();
    
    for(Opportunity op : [SELECT Id, Name FROM Opportunity WHERE StageName = 'Closed Won' AND Id IN :Trigger.New]){
        tsk.add(new Task(Subject='Follow Up Test Task',WhatId = op.Id));
    }
    if(tsk.size() > 0 ){
        insert tsk;
    }
        
}

 
shradha mhaskeshradha mhaske
Apex Trigger Code is 
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
 List<Task> taskList = new List <Task>();
     For (Opportunity opps: [Select ID, name from Opportunity where stageName ='Closed Won' and ID IN :Trigger.New])
     {
        
      Task myTask = new Task();
         myTask.Subject = ('Follow Up Test Task');
         myTask.WhatId = opps.id;
         taskList.add(myTask);
     
         
     }
    if(taskList.size()>0)
    {
        insert taskList;
    }
}
Cross check that whether Apex trigger ClosedOpportunityTrigger is working or not  - 
Insert or update any opportunity record stage field as 'Closed Won' and saved it.
It will automatically assign Follow up task with Subject to the opportunity.
Ashutosh Sharma 83Ashutosh Sharma 83
Keep on getting error :

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. The input parameter "oppProducts_Original" can't accept values of type null. Error ID: 1314204860-19430 (-876674778): []


Can someone help!
Keith AshleyKeith Ashley
Hi Ashutosh,  check Flows or Process Builder for Opportunity Management and disable it.  That should fix your error.  Likely another hand-on challenge solution is interfering with your new trigger.
Sayed Sajid AliSayed Sajid Ali
This code works directly copy-paste the code


trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {
    
  if(trigger.isInsert || trigger.isUpdate){
    UpdateOpportunity.checkOpportunityStage(trigger.new);
    }
}
TRIGGER HANDLER:
public class UpdateOpportunity{
    public static void checkOpportunityStage(List<Opportunity> opportunityList){
    if(opportunityList.size()>0){
        List<Task> taskList=new List<Task>();
            for(Opportunity op:opportunityList){
                if(opp.StageName=='Closed Won'){
                Task task1=new Task();
                task1.Subject='Follow Up Test Task';
                task1.WhatId=op.Id;
                taskList.add(task1);                      
            }
           }
        if(taskList.size()>0){
           insert taskList;
        }
    }
}
Scott Song 4Scott Song 4
Try this, it is simple, but will work. You have to deactivate your process"Opportunity Management" before you take the challenge.


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

    list<Task> tasklist= new list<Task>();
    
    for(opportunity a:[SELECT ID,stagename FROM opportunity WHERE ID IN:Trigger.New AND StageName='Closed Won']){
        
        tasklist.add(new task(Subject='Follow Up Test Task',WhatId=a.id));
    }
    
    insert tasklist;
}
Ziaul AnsariZiaul Ansari
trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {
    
    List<Task> opp=new List<Task>();
    List<Opportunity> newOpportunity=[SELECT id,Name,StageName FROM Opportunity WHERE Id In :Trigger.new AND StageName='Closed won' ];
   
    
    for(Opportunity op : newOpportunity)
    {
       opp.add(new Task(WhatId=op.Id,Subject='Follow Up Test Task'));
    
    }
    if(Trigger.isInsert)
    {
        insert opp;
    }
    else
    {
         update opp;
    }
       
}
Sayed Sajid AliSayed Sajid Ali
Try this it works:

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    List<Task> taskList = new List<Task>();
    for(Opportunity o: Trigger.New){
        if(o.StageName == 'closed won'){
            taskList.add(new Task(Subject='Follow Up Test Task', whatId=o.Id));
        }
    }
    
    if(taskList.size() > 0){
        insert tasklist;
    }
}
ani ghoani gho
/*Thanks.....reading all above and the jist to make it work for me for me for me......and my coding experience here....*/

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {    
      List<Task> taskList = new List<Task>(); //create the taskList
    
    for(Opportunity oppt : Trigger.New){//iterate over opportunity to add the new task with required subject and id.....
        if('Closed Won'.equals(oppt.StageName)){
            taskList.add(new Task(Subject='Follow Up Test Task',WhatId=oppt.Id)); //add to taskList now in memory           
        }        
    }
    
     if(Trigger.isInsert){//very important else the code fails do when insert, insert[new Entry]
        insert taskList; //now in db... persist
         }
        else {// when update [mutating the existing one]
         update taskList;       
    }
    
    
}