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
siree gantisiree ganti 

Apex trigger error

Hi All,
Following apex trigger fails to create the task as intended. I was able to get rid of dml exceptions, but still no task.  Please advise.

trigger addNewTaskToAccountOwner on Opportunity (after insert, after update) {
for (Opportunity myOppty : Trigger.new) {
if ((myOppty.StageName != 'Closed Won') &&(myOppty.StageName!='Closed Lost') && (myOppty.Account != NULL)) {
Task myTask = new Task();
myTask.OwnerId = myOppty.Account.OwnerId;
myTask.Subject = 'Automatic task';
myTask.Status = 'Not Started';
myTask.Priority = 'Normal';
insert myTask;
}
}
}


 
sandeep sankhlasandeep sankhla
Hi siree,

As a best practise we should not use DML inside for loop..you can create a list of task and store all tasks in that list and outside the for loop you can insert all of them to avoid error..

trigger addNewTaskToAccountOwner on Opportunity (after insert, after update) {
   list<Task> lstTask = new list<Task>();
    for (Opportunity myOppty : Trigger.new) {
       if ((myOppty.StageName != 'Closed Won') &&(myOppty.StageName!='Closed Lost') && (myOppty.Account != NULL)) {
          Task myTask = new Task();
          myTask.OwnerId = myOppty.Account.OwnerId;
          myTask.Subject = 'Automatic task';
          myTask.Status = 'Not Started';
          myTask.Priority = 'Normal';
          lstTask .add(myTask);

         }
     }
     if(!lstTask.isEmpty() )
      insert lstTask ;
}
Replace your code with this ...
please mark this as best answer if it solves your issue...
 
Pankaj_GanwaniPankaj_Ganwani
Hi Siree,

Just following up here. At this statement myTask.OwnerId = myOppty.Account.OwnerId; we cannot get Account's owner id since trigger only returns the field value upto one ancestor level i.e. you can only get related accountid of opportunity record. To get the OwnerId of Account you will have to perfrom soql and then assign the value to Task.OwnerId field.

Please let me know if this helps you out.

Thanks,
Pankaj
siree gantisiree ganti
Thanks Pankaj Ganwani 3.  I did the soql, but still no task. Any thoughts?  Here's the code:

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

List <Task> myTask = new List <Task>();
for (Opportunity myOppty : Trigger.new) {
        List <Account> myacctownerid = [Select OwnerId From Account Where (Name = :myOppty.AccountId)];
        
    if ((myOppty.StageName != 'Closed Won') &&(myOppty.StageName!='Closed Lost') && (myOppty.AccountId != NULL)) {
   
    if (myacctownerid.size() > 0) {
    myTask.add(new Task(OwnerId = myacctownerid[0].Id, Subject = 'Automatic', Status = 'Not Started', Priority = 'Normal'));
    
 }
        }
}
// DML method to insert the new task
Database.SaveResult[] sr = Database.insert(myTask,false);

for (Database.SaveResult sr : srList){
 if(sr.isSuccess()) { // Operation successful, get task record id
 System.debug('Successfully inserted task. Task id: ' +sr.getId());}
 else { //operation failed, get all errors
   for (database.Error err : sr.geterrors()) {
   System.debug(' The following error has occured: ' +err.getMessage());
   System.debug(' Fields that affected this error: ' +err.getFields());
   }
   }
 }
 }


 
Pankaj_GanwaniPankaj_Ganwani
Hi Siree,

I have made some updates in your code. Please try:

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

List <Task> myTask = new List <Task>();
for (Opportunity myOppty : Trigger.new) {
        List <Account> myacctownerid = [Select OwnerId From Account Where Id = :myOppty.AccountId];
        
    if ((myOppty.StageName != 'Closed Won') &&(myOppty.StageName!='Closed Lost') && (myOppty.AccountId != NULL)) {
   
    if (myacctownerid.size() > 0) {
    myTask.add(new Task(OwnerId = myacctownerid[0].OwnerId, Subject = 'Automatic', Status = 'Not Started', Priority = 'Normal'));
    
 }
        }
}
// DML method to insert the new task
Database.SaveResult[] sr = Database.insert(myTask,false);

for (Database.SaveResult sr : srList){
 if(sr.isSuccess()) { // Operation successful, get task record id
 System.debug('Successfully inserted task. Task id: ' +sr.getId());}
 else { //operation failed, get all errors
   for (database.Error err : sr.geterrors()) {
   System.debug(' The following error has occured: ' +err.getMessage());
   System.debug(' Fields that affected this error: ' +err.getFields());
   }
   }
 }
 }
siree gantisiree ganti
Hi Pankaj, Thanks, that works. Appreciate the prompt responses! Siree