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
Mehul pMehul p 

Why this trigger won't insert task for rest of the contacts?

This trigger inserts and updates contact fields fine for the first contact but when there are multiple contacts in Task, the task does not update contact fields for the rest of the contacts. What am I doing wrong? Thank you in advance!
if (Trigger.isafter && Trigger.isInsert){ 
     System.debug('I RAN INSERT');


public class ActivityHandlerClass {
        public static void insertContact(List<Task> tks){ // Trigger.New comes as List here
        Set<Id> ContactIds = new Set<Id>();
        List<Contact> ContactList = new List<Contact>();

        List<Task> taskContacts = [SELECT Id, Subject, (SELECT RelationId, Relation.Name from TaskRelations) FROM Task WHERE id in:tks];
        System.debug('Print Task Contacts: ' + taskContacts);

        for(Task ti: taskContacts)
            for(TaskRelation tRel: ti.TaskRelations)
               System.debug('Print Task Contacts: ' + tRel);
                System.debug('Print Task Contact Size: ' + ti.TaskRelations.Size());
                If(ti.TaskRelations.Size() >0){
                  System.debug('Print added to ContactIds: ' + ContactIds);


                List<Contact> relatedContacts = [select id,Last_Contact_Date__c,LastActivityDate, Last_Activity_Subject__c from Contact where id in:ContactIds];
                System.debug('Print RelatedContacts :' + relatedContacts);

        for(Task t :tks)
                for(Contact con : relatedContacts)
                  If(t.ActivityDate >=con.Last_Contact_Date__c)
                    con.Last_Activity_Subject__c = t.subject;
                    con.Last_Activity_Date__c = t.ActivityDate;

                         System.debug('Printining that ADDDDDDDDDDDDDDDDDDDDD   ran');  
                         System.debug('ContactList is being printed:' + ContactList); 
                         System.debug('ContactList ID is being printed:***********' +; 
            System.debug('Update ContactList***************');

            upsert ContactList; 
  } // End of Insert Method

Rounak SharmaRounak Sharma
Hello Mehul,

I would suugest for 2 lists and instead of upsert go with insert and update.

Please let me know if it helps.