+ Start a Discussion
SFDC-DMGSFDC-DMG 

Trigger to populate Most Recent Task Date on related record (filtered for certain tasks)

Hi All,

 

I have the below code that counts the number of a certain type of activity related to a given record. I want to update this to also pull in the date of the most recent task that is in the list. I have added a command to sort the tasks by date, but I'm getting stuck on how to select the most recent date of the generated list and populate that on the lead/contact record. Can anyone help with this?

 

Thanks!

 

trigger UpdateLeadContactOppDemoDeliveredTasks on Task (after delete, after insert, after undelete,
after update) {

// Updated on 2.28.13 to include only leads and contacts - opportunities were separated out


// Declare the variables

public set<Id> LeadIDs = new Set<Id>();
public list<Lead> LeadsToUpdate = new List<Lead>();
public set<Id> ContactIDs = new Set<Id>();
public list<Contact> ContactsToUpdate = new List<Contact>();




// Build the list of Leads and Contacts to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
    for(Task t: Trigger.new){
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('00Q'))
    LeadIDs.add(t.WhoId);
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('003'))
    ContactIDs.add(t.WhoId);


    }
}

if(Trigger.isDelete || Trigger.isUpdate){
    for(Task t: Trigger.old){
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('00Q'))
    LeadIDs.add(t.WhoId);
    if(t.whoid!=null && string.valueOf(t.WhoId).startsWith('003'))
    ContactIDs.add(t.WhoId);
    }
}

// Update the Leads

if(LeadIDs.size()>0){
for(Lead l: [Select l.Id, l.Demos_Delivered_Count__c,
(Select Id, ActivityDate From Tasks where Status = 'Demo Delivered' Order by ActivityDate DESC )
From Lead l where Id in :LeadIDs])
LeadsToUpdate.add(new Lead(Id=l.Id, Demos_Delivered_Count__c = l.Tasks.size()));
update LeadsToUpdate;
}
if(LeadstoUpdate != null && !LeadsToUpdate.isEmpty())
Database.update(LeadsToUpdate);

// Update the Contacts

if(ContactIDs.size()>0){
for(Contact c: [Select c.Id, c.Demo_Delivered_Count__c,
(Select Id, ActivityDate From Tasks where Status = 'Demo Delivered' Order by ActivityDate DESC)
From Contact c where Id in :ContactIDs])
ContactsToUpdate.add(new Contact(Id=c.Id, Demo_Delivered_Count__c  = c.Tasks.size()));
update ContactsToUpdate;
}
if(ContactstoUpdate != null && !ContactsToUpdate.isEmpty())
Database.update(ContactsToUpdate);


}

k_bentsenk_bentsen

If you have a custom date field for your Leads and Contacts with something say, "Last_activity_date__c" you could do something like the below on your lines where you're building the update lists.

 

 

LeadsToUpdate.add(new Lead(Id=l.Id, Demos_Delivered_Count__c = l.Tasks.size(), Last_activity_date__c = l.Tasks[Tasks.size()-1].ActivityDate ));

 

ContactsToUpdate.add(new Contact(Id=c.Id, Demo_Delivered_Count__c  = c.Tasks.size(), Last_activity_date__c = c.Tasks[Tasks.size()-1].ActivityDate));

PenchuReddyPenchuReddy
Hi,
I am facing one issue in above trigger.
if i created first task with Activity__c =='Call' with Activitydate= 1/1/17
then  Last_Call_Date__c=1/1/17 (correct)
        First_Call_Date__c = 1/1/17 (correct)

and, again if i created first task with Activity__c =='Call' with Activitydate= 2/1/17
then  Last_Call_Date__c=2/1/17 (correct)
        First_Call_Date__c=1/1/17 (correct)

(its same for First Task if it is Activity__c =='Email')

but problem is...
if i created second task on same lead 
example: first task Activity__c =='Call'
              second task Activity__c =='Email'
or viceversa

then, here second task Activity__c =='Email' with Activitydate= 3/1/17
then,    Last_Email_Date__c =3/1/17
            First_Email_Date__c = First_Call_Date__c(this field value updating. but this field value not showing in record. found in debuglogs) (wrong here)

if i create first and second task with same date, then no issue
if i created both tasks with different dates then issue coming

i found what is the issue, but unable to solve that. 
the issue is... DESC and ASC order of activitydate.

for second task... it taking first task activitydate in ASC order(see above example)
as per code its correct. but i want as per how it is taking for first task.

i hope you understand. please help me on this.
Thanks.
here is my code:
    
trigger TaskUpdateLead on Task (after delete, after insert, after undelete, after update) {
Set<ID> LeadIds = new Set<ID>();
String leadPrefix = Lead.SObjectType.getDescribe().getKeyPrefix();
if(trigger.new!=null){
    for (Task t : Trigger.new) {
     if (t.WhoId!= null && string.valueof(t.WhoId).startsWith(leadPrefix) ) {

if(!LeadIds.contains(t.WhoId)){
LeadIds.add(t.WhoId);
}
}
}
}
if(trigger.old!=null){
    for (Task t2 : Trigger.old) {
     if (t2.WhoId!= null && string.valueof(t2.WhoId).startsWith(leadPrefix) )
         {
if(!LeadIds.contains(t2.WhoId)){
LeadIds.add(t2.WhoId);
}
}
}
}
     if (LeadIds.size() > 0){
//------------------TodaysEmailCallCount------------
List<Lead> TodaysEmailCount = [select id,Email_Count_Today__c,(select id,ActivityDate from Tasks where Activity__c='Email' and Status='Completed' and CreatedDate=today) from Lead where Id IN : Leadids];

List<Lead> TodaysCallCount= [select id, Call_Count_Today__c,(select id,ActivityDate from Tasks where Activity__c='Call'and Status='Completed' and CreatedDate=today) from Lead where Id IN : Leadids];

List<Lead> leadsUpdatableEmail = new List<Lead>();
List<Lead> leadsUpdateCall = new List<Lead>();
//-------------------------------------------
List<Lead> leadsWithTasks = [select id,Email_Count__c,Email_Count_Today__c,(select id,ActivityDate from Tasks where Activity__c='Email' and Status='Completed') from Lead where Id IN : Leadids];

List<Lead> leadsWithTask = [select id,Call_Count__c, Call_Count_Today__c,(select id,ActivityDate from Tasks where Activity__c='Call'and Status='Completed') from Lead where Id IN : Leadids];

List<Lead> leadsUpdatable = new List<Lead>();
List<Lead> leadsUpdate = new List<Lead>();
List<Lead> lastEmail = new List<Lead>();
List<Lead> firstEmail = new List<Lead>();
List<Lead> lastCall = new List<Lead>();
List<Lead> firstCall = new List<Lead>();

for(Lead L : leadsWithTasks){

L.Email_Count__c = L.Tasks.size();
leadsUpdatable.add(L);
}
if(leadsUpdatable.size()>0){

update leadsUpdatable;
}

//-----------------Todays Email Count------------------------
for(Lead LE : TodaysEmailCount ){
LE.Email_Count_Today__c=LE.Tasks.size();
leadsUpdatableEmail.add(LE);
}
if(leadsUpdatableEmail.size()>0){

update leadsUpdatableEmail;
}
//--------------------------------------------
for(Lead L : leadsWithTask){

L.Call_Count__c = L.Tasks.size();
leadsUpdate.add(L);
}
if(leadsUpdate.size()>0){

update leadsUpdate;
}
//---------------------Todays Call Count---------------------
for(Lead LE : TodaysCallCount){
LE.Call_Count_Today__c=LE.Tasks.size();
leadsUpdateCall.add(LE);
}
if(leadsUpdateCall.size()>0){

update leadsUpdateCall;
}
//-------------------------------------------
for(Lead ld : [Select Id, Name,
    (Select Id, Subject,ActivityDate,Activity__c,FastCall__Call_Notes__c,CallDisposition from Tasks where Status='Completed' Order by ActivityDate DESC Limit 5    ) 
    from Lead where Id IN : Leadids]){
for(task t:ld.tasks)
{
if(t.Activity__c =='Call')
{
ld.Last_Call_Date__c = t.activitydate;
lastCall.add(ld);
}
else
{
ld.Last_Email_Date__c = t.activitydate;
lastEmail.add(ld);
}
update lastCall;
update lastEmail;
}
}
for(Lead ld : [Select Id, Name,
    (Select Id, Subject,ActivityDate,Activity__c from Tasks where Status='Completed' Order by ActivityDate ASC Limit 1) 
    from Lead where Id IN : Leadids]){
for(task t:ld.tasks)
{
if(t.Activity__c =='Call')
{
ld.First_Call_Date__c = t.activitydate;
firstCall.add(ld);
}
else
{
ld.First_Email_Date__c = t.activitydate;
firstEmail.add(ld);
}
}
update firstCall;
update firstEmail;
}
}
}