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
Kellie MillardKellie Millard 

Apex Trigger on Tasks to populate a "Date of Last activity" custom field

Scenario:
I have been asked to present information at an Account, Opportunity, Contact and Lead level where we have a simple date field that shows the Date of Last Activity for each of these objects. However, I need to specify which activity... ensuring that it is only giving us the teams activity (and not marketing generated) 

So Far:
I have a custom field against the task object - "Hubspot generated" - Y/N which is populated by workflow. 

I have created new custom formula (date) fields against each of the objects (which are currently pulling in the date of last activity (any activity including hubspot generated).  

I had previously been coming at this from a workflow or formula based approach but now understand Apex is the way to go.. but I have no experience in this whatsoever! 

trigger lastactivitydate ex hubspot (after insert, after update)
?????
and then i am lost in code! I believe i need to incorporate Task = Closed, Hubspot Generated = No  but not sure how to present this.

Any helpers?  Thanks In Advance!
Kellie 
Jasper WallJasper Wall

Hi Kellie,

Use a batch class to achieve this. below is the code to populate latest task activity on Contacts. you can use same pattern to work of Account & Opportunity.
 
global class PopulateLatestTaskOnContact implements Database.Batchable<sObject>{

   global final String Query='SELECT Id,Latest_Task__c,(SELECT Id, whoId,Subject, ActivityDate, Status, IsHighPriority, CreatedDate, LastModifiedById, LastModifiedDate,TaskSubtype FROM Tasks) FROM Contact';
   List<Task> tasks=new List<Task>();
   DateTime latest=DateTime.newInstance(0,0,0);
   List<Contact> contactsToUpdatelist=new List<Contact>();
   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<Contact> scope){
       for(Contact c:scope){
           for(Task t:c.tasks){
               if(t.LastModifiedDate>latest){
                   latest=t.LastModifiedDate;
                   c.Latest_Task__c=t.Subject;
               }
           }
           contactsToUpdatelist.add(c);
       }  
        try{
           update contactsToUpdatelist;
       }catch(Exception e){
           System.debug(e);
       }
       System.debug('Contacts Updated : # '+contactsToUpdatelist.size());
   }

   global void finish(Database.BatchableContext BC){
      
   }
}
Fine more details in using batch apex in
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

Mark as the best answer if it helps,

Thanks,
Balayesu
Kellie MillardKellie Millard
Thank you Balayesu  -  This looks as though it will give the latest task which is what I am looking for but can I check will this exclude the marketing generated activity (my hubspot generated = no)  as our hubspot instance is synced with our salesforce instance and such activities also appear as tasks as far as I understand.  I was expecting to have to add in some additional IF criteria?

 
Jasper WallJasper Wall
yes, add an additional condition like,
if(t.myhubgenerated!=null && t.myhubgenerated=='no'){
if(t.LastModifiedDate>latest){
      latest=t.LastModifiedDate;
      c.Latest_Task__c=t.Subject;
 }
}

 
Kellie MillardKellie Millard
im getting an error message .... whats wrong?
line breaks not allowed in string literals - line 12?   if(t.Status__c!='Completed'&& t.Status__c!='Completed){{



Here is my code:
public class PopulateCustomLastActivity implements Database.Batchable<sObject>{
public final String Query='SELECT Id,Last_Activity_Ex_Hb,(LastActivity FROM Tasks) FROM Contact ';
   List<Task> tasks=new List<Task>();
   DateTime latest=DateTime.newInstance(0,0,0);
   public Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }
public void execute(Database.BatchableContext BC, List<Contact> scope){
       for(Contact c:scope){
           for(Task t:c.tasks){
             if(t.Hubspot_generated__c!=null && t.Hubspot_generated__c=='no'){
             if(t.Status__c!='Completed'&& t.Status__c!='Completed){{
if(t.LastActivity>latest){
    latest=t.LastActivity;
  c.Last_Activity_Ex_Hb=t.Subject;
 }
}
contactsToUpdatelist.add(c);
       } 
               try{
           update contactsToUpdatelist;
       }catch(Exception e){
           System.debug(e);
       }
       System.debug('Contacts Updated : # '+contactsToUpdatelist.size());
   }   
 }
}
}
                    }