+ Start a Discussion
Nishant Kumar 107Nishant Kumar 107 

Execution of AfterInsert caused by: System.SObjectException

I am getting below exception
Execution of BeforeInsert caused by: System.SObjectException: DML statement cannot operate on trigger.new or trigger.old: Class
I create a class which insert task for account object while creating task for a Lead object, below i hardcoded the account whatId. I created trigger for Task and call CreateTaskInAccount.createTask() from trigger, but its not happening like so.
Please share your feedback.

public class CreateTaskInAccount
{
 public void createTask(List<Task> TaskFromTrigger)
  {
  
    Account targetWhatId= [SELECT a.Id FROM Account a where a.Name='NishantAccount'];
    
    List<Task> tskList= new List<Task>();
    
    for(Task varTask: TaskFromTrigger)
    {
      Task tsk= new Task();
      
      tsk=varTask;
      tsk.WhatId=targetWhatId.Id;
            
                  
      tskList.Add(tsk);
    }
  
    Database.Insert(tskList);
  }
}
------------------------------------
trigger CreateTaskInAccount on Task (before insert, before update) {

  List<Task> lTask = new List<Task>();
  
    
  CreateTaskInAccount objAccount=new CreateTaskInAccount();
  objAccount.createTask(Trigger.new);
}

Tanks in advance
Best Answer chosen by Nishant Kumar 107
Amit Chaudhary 8Amit Chaudhary 8

Please use before insert Trigger :-
 
trigger CreateTaskInAccount on Task (before insert) {

  List<Task> lTask = new List<Task>();
  
    
  CreateTaskInAccount objAccount=new CreateTaskInAccount();
  objAccount.createTask(Trigger.new);
}
Apex class like below
public class CreateTaskInAccount
{
	public void createTask(List<Task> TaskFromTrigger)
	{
  
		Account targetWhatId= [ SELECT Id FROM Account where Name='NishantAccount' ];
		
		for(Task varTask: TaskFromTrigger)
		{
			varTask.WhatId=targetWhatId.Id;
		}
	}
}


Let us know if this will help you

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please update your code like below
public class CreateTaskInAccount
{
	public void createTask(List<Task> TaskFromTrigger)
	{
  
		Account targetWhatId= [ SELECT Id FROM Account where Name='NishantAccount' ];
		
		for(Task varTask: TaskFromTrigger)
		{
			varTask.WhatId=targetWhatId.Id;
		}
	}
}

Let us know if this will help you
 
Tarun J.Tarun J.
Hello Nishant,

In you code you are trying to insert task record which is being passed from trigger. You cannot perform DML operation on it. In order insert new task for Account, you have to create a new task instance and insert it.

Try below code and modify it as per your need:
public class CreateTaskInAccount
{
	public void createTask(List<Task> TaskFromTrigger)
	{

		Account targetWhatId= [SELECT a.Id FROM Account a where a.Name='NishantAccount'];

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

		for(Task varTask: TaskFromTrigger)
		{
			Task tsk= new Task();
				
			tsk.WhatId = targetWhatId.Id;
			tsk.Priority = varTask.Priority;
			tsk.Status = varTask.Status;
			//Add More field which you want to copy from Lead task to Account Task            
					  
			tskList.add(tsk);
		}
		if(tskList.size() > 0){
			Database.Insert(tskList);
		}
	}
}



-Thanks,
TK

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.
Sumit Sharma 186Sumit Sharma 186
We cannot insert or update records in before insert or before update trigger because the records are already going to be inserted or updated in the before trigger:

Please use following block of code:

trigger CreateTaskInAccount on Task (after insert, after update) {
  CreateTaskInAccount objAccount=new CreateTaskInAccount();
  objAccount.createTask(Trigger.new);
}
 
public class CreateTaskInAccount
{
 public void createTask(List<Task> TaskFromTrigger)
  {
  
    Account targetWhatId= [SELECT a.Id FROM Account a where a.Name='NishantAccount'];
    
    List<Task> tskList= new List<Task>();
    
    for(Task varTask: TaskFromTrigger)
    {
      Task tsk= new Task();
      tsk=varTask;
      tsk.WhatId=targetWhatId.Id;
      tsk.WhoId= varTask.WhoId;    
                  
      tskList.Add(tsk);
    }
  
    Database.Insert(tskList);
  }
}


Sr.Salesforce Developer
Mirketa Inc (http://www.mirketa.com/)
Nishant Kumar 107Nishant Kumar 107
Hi Sumit,

I write below code then it starts working,  Database.Insert(tskList) gives DML error, but changing insert to uodate strats working. I am still confuse why Insert is not working.

public class CreateTaskInAccount
{
 public void createTask(List<Task> TaskFromTrigger)
  {
  
    List<Task> lstTskFromTrigger=[
    SELECT AccountId,ActivityDate,CallDisposition,CallDurationInSeconds,CallObject,CallType,
    ConnectionReceivedId,ConnectionSentId,CreatedById,CreatedDate,Description,Id,IsArchived,
    IsClosed,IsDeleted,IsHighPriority,IsRecurrence,IsReminderSet,LastModifiedById,LastModifiedDate,
    OwnerId,Priority,RecurrenceActivityId,RecurrenceDayOfMonth,RecurrenceDayOfWeekMask,
    RecurrenceEndDateOnly,RecurrenceInstance,RecurrenceInterval,RecurrenceMonthOfYear,
    RecurrenceRegeneratedType,RecurrenceStartDateOnly,RecurrenceTimeZoneSidKey,RecurrenceType,
    ReminderDateTime,Status,Subject,SystemModstamp,TaskSubtype,WhatId,WhoId FROM Task
    WHERE Id IN : Trigger.newMap.keySet()
    ];
    
    
    Account targetWhatId= [SELECT a.Id FROM Account a where a.Name='NishantAccount'];
    List<Task> tskList= new List<Task>();
    
    for(Task varTask: lstTskFromTrigger)
    {
      Task tsk= new Task();
      tsk=varTask;
      tsk.WhatId=targetWhatId.Id;
      tskList.Add(tsk);
    }
    
    //Database.Insert(tskList);
    update tskList;
  }
}
Nishant Kumar 107Nishant Kumar 107
For Trigger i also made changes like
trigger CreateTaskInAccount on Task (after insert) {

  List<Task> lTask = new List<Task>();
  
    
  CreateTaskInAccount objAccount=new CreateTaskInAccount();
  objAccount.createTask(Trigger.new);
}
Amit Chaudhary 8Amit Chaudhary 8
Hi Nishant,

It look like you only want to update account then no need to update same record again you can try below code
Trigger
trigger CreateTaskInAccount on Task (after insert) {

  List<Task> lTask = new List<Task>();
  
    
  CreateTaskInAccount objAccount=new CreateTaskInAccount();
  objAccount.createTask(Trigger.new);
}
Apex class
public class CreateTaskInAccount
{
	public void createTask(List<Task> TaskFromTrigger)
	{
  
		Account targetWhatId= [ SELECT Id FROM Account where Name='NishantAccount' ];
		
		for(Task varTask: TaskFromTrigger)
		{
			varTask.WhatId=targetWhatId.Id;
		}
	}
}


No need to extra DML. Let us know if this will help you
 
Nishant Kumar 107Nishant Kumar 107
Hi Amit,

I am getting below error message if i directly update WhatId property, any help/comment.

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CreateTaskInAccount caused an unexpected exception, contact your administrator: CreateTaskInAccount: execution of AfterInsert caused by: System.FinalException: Record is read-only: Class.CreateTaskInAccount.createTask: line 10, column 1
 
Amit Chaudhary 8Amit Chaudhary 8

Please use before insert Trigger :-
 
trigger CreateTaskInAccount on Task (before insert) {

  List<Task> lTask = new List<Task>();
  
    
  CreateTaskInAccount objAccount=new CreateTaskInAccount();
  objAccount.createTask(Trigger.new);
}
Apex class like below
public class CreateTaskInAccount
{
	public void createTask(List<Task> TaskFromTrigger)
	{
  
		Account targetWhatId= [ SELECT Id FROM Account where Name='NishantAccount' ];
		
		for(Task varTask: TaskFromTrigger)
		{
			varTask.WhatId=targetWhatId.Id;
		}
	}
}


Let us know if this will help you
This was selected as the best answer
Nishant Kumar 107Nishant Kumar 107
Thanks Amit, i have to correct logic for Who ID/What ID, seems logic is incorrect there.