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
uHaveOptionsuHaveOptions 

APEX Trigger on "My_Last_Call_Date__c"

Hello Team,

I have an APEX trigger but would like to get the LAST CALL DATE based on user.  So there could be 100 calls but if I called them 1/1/9015 and since I'm the user it will show the last call date of my activity.  I know it will change for everyone.  I create a field call My_Last_Call_Date__c.

Thoughts?
 
trigger CallDate on Task (after insert, after update, after delete) 
{
    Set<Id> con_set = new Set<Id>();
    List<Contact> con_list = new List<Contact>();
    for( Task T: Trigger.new )
    {
        if(String.valueof(T.whoid).startsWith('003') && T.Status=='Completed' && T.Subject=='Call' )
        {
            con_set.add(T.whoid);
        }
    }
     
     for(AggregateResult aggregateResult:[SELECT max(createdDate)MaxCDate,whoid FROM Task WHERE whoid IN: con_set AND Status ='Completed' AND (subject LIKE 'call%' OR subject LIKE 'outbound%') group By whoid])
     {
        con_list.add(new Contact(Id=(id)aggregateResult.get('whoid'),Last_Call__c=date.valueof(aggregateResult.get('MaxCDate'))));
     }
     
    try
    {
     
         if(con_list !=null && con_list.size()>0)
         {
             update con_list;
         }
     
    }Catch(Exception e){
         system.debug('Exception ***'+e.getMessage());
      
     }

}

thanks in advance
Donald BlayDonald Blay
I think you can probably simplify this process a bit.  Here's what I would suggest:
  • Loop through all the new tasks (the loop that starts on line 5) to build a list of Ids of the related Contact ID's (the whoIds).  
  • Then outside of the loop you can then querey Contacts with those contact Id's and put them into a Map (index by contact ID). This will give you the Contact you need to update.  
  • Then loop through the Tasks again, get the related contact from the map, and if the Task's date is greater than the contacts's current My_Last_Call_Date__c then set the My_Last_Call_Date__c to the Task's date. 
  • Then finally update the list of contacts.  (like you're doing on line 23)
Hope that helps.