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
akshay desai 9akshay desai 9 

trigger on task issue

I want to write a trigger when user insert or change name(whoid) of task then there is field in task object that has to be change with contact name
trigger taskupdatetrigger on Task (after insert,after update) {
    list<task>tasklist=new list<task>();
    list<contact>contactlist=[select id,name from contact];
       id taskid;
    id contactid;
    for(task taskobj:trigger.new){
        taskid=taskobj.id;
        system.debug('task id'+taskid);
        for(contact conobj:contactlist){
            if(taskobj.WhoId==conobj.Id){
            system.debug('inside if');
            /taskobj.POC_name__c=conobj.Name;
                system.debug('POC_name__c'+taskobj.POC_name__c);
        }
            
        }
        
    }
    system.debug('contactlist'+contactlist);
}

this is giving me error on saving "execution of AfterUpdate caused by: System.FinalException: Record is read-only Trigger.Calendar_trigger: line 12, column 1"
Best Answer chosen by akshay desai 9
Susan TaylorSusan Taylor
Hi Akshay,

The general rule is that you make changes to the record that is being inserted/udpated in the before triggers (since that saves you a DML statement), and any other objects in the after triggers.

Also, I noticed you are looping through all your contacts for each Task.  A very common pattern you'll see is to use a Map variable to store records, which can then be retrieved by Id.  It saves a lot of processing time:
trigger taskupdatetrigger on Task (before insert, before update) { 
     Map<Id, Contact> contacts = New Map<Id, Contact>([SELECT Id, Name FROM Contact]); 

     for(Task taskobj: trigger.new){ 
          if(contacts.containsKey(taskObj.WhoId)) { 
               taskobj.POC_name__c = contacts.get(taskObj.WhoId).Name ; 
         } 
     } 
}

 

All Answers

Susan TaylorSusan Taylor
Hi Akshay,

The general rule is that you make changes to the record that is being inserted/udpated in the before triggers (since that saves you a DML statement), and any other objects in the after triggers.

Also, I noticed you are looping through all your contacts for each Task.  A very common pattern you'll see is to use a Map variable to store records, which can then be retrieved by Id.  It saves a lot of processing time:
trigger taskupdatetrigger on Task (before insert, before update) { 
     Map<Id, Contact> contacts = New Map<Id, Contact>([SELECT Id, Name FROM Contact]); 

     for(Task taskobj: trigger.new){ 
          if(contacts.containsKey(taskObj.WhoId)) { 
               taskobj.POC_name__c = contacts.get(taskObj.WhoId).Name ; 
         } 
     } 
}

 
This was selected as the best answer
akshay desai 9akshay desai 9
Thanks Susan for your help