+ Start a Discussion
rahul seth 6rahul seth 6 

I wanna create a trigger that queries the latest task (based on created/modified date) on Account. It works fine on AfterInsert,but I wanna have After Update functionality as well. Can anyone help

My code is as follows:
 
trigger LatestCreatedDate on Task (after insert,after update) {

        TriggerHandler objTriggerHandler = new TriggerHandler();
        if( trigger.isInsert){
            objTriggerHandler.onAfterInsert(trigger.new);
        } 
        if(trigger.isUpdate){
            objTriggerHandler.onAfterUpdate(trigger.new , trigger.old);
        }
}

Handler class code:
 
public class TriggerHandler{
    List<DateTime> lstDateTime = new List<DateTime>();
    public void onAfterInsert(List<Task> lsttsk)
    {
     Set<Id> setId=new Set<Id>();
     for(Task objtask : lsttsk)
     {
         setId.add(objtask.WhatId);
     }
     List<Account> lstAccount=[Select Id,Recently_Added_Task_Date__c,(Select Id,LastModifiedDate FROM Tasks Order by LastModifiedDate desc Limit 1) From Account WHERE Id IN: setId];
       for(Account objAccount : lstAccount)
       {
           for(Task objtas : objAccount.Tasks)
           objAccount.Recently_Added_Task_Date__c = objtas.LastModifiedDate;

       }update lstAccount;
    }
}

 
Amit Chaudhary 8Amit Chaudhary 8

Please try to update your handler class like below
public class TriggerHandler
{
    public void onAfterInsert(List<Task> lsttsk)
	{
		UpdateAccount(lsttsk);
	}

    public void onAfterUpdate(List<Task> lsttsk , List<Task> lstOldtsk)
	{
		UpdateAccount(lsttsk);
	}
	
    List<DateTime> lstDateTime = new List<DateTime>();
	public void UpdateAccount(List<Task> lsttsk)
    {
		Set<Id> setId=new Set<Id>();
		for(Task objtask : lsttsk)
		{
			setId.add(objtask.WhatId);
		}
		List<Account> lstAccount=[Select Id,Recently_Added_Task_Date__c,(Select Id,LastModifiedDate FROM Tasks Order by LastModifiedDate desc Limit 1) From Account WHERE Id IN: setId];
		
		for(Account objAccount : lstAccount)
		{
			for(Task objtas : objAccount.Tasks)
			   objAccount.Recently_Added_Task_Date__c = objtas.LastModifiedDate;
		}
		update lstAccount;
    }
}
Please check below post for trigger framework
1) http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html

Let us know if this will help you

Thanks
Amit Chaudhary