Trigger to update latest due date of task on Opportunity

Create a new custom field on opportunity called Update_Due_Date_of_Task__c (Date/Time) and create the below trigger on task object. 

Output : If there are multiple tasks on opportunity the above custom field will be updated by due date which is greater from all task's due date.


Trigger updateLastActvtyUpdateOnOpty on Task(after update, after insert) {

    Datetime lastUpdatedDate;
    Set < String > whatIDs = new Set < String > ();
    for (Task tskObj: Trigger.new) {
        if (tskObj.whatId != null && tskObj.ActivityDate != null) {
            whatIDs.add(tskObj.whatId);
        }
    }
    If(whatIDs.size() > 0) {
        Task taskObj = [select Id, ActivityDate, WhatId from Task where WhatId =: whatIDs
                                 order by ActivityDate DESC LIMIT 1]; 
        lastUpdatedDate = taskObj.ActivityDate;
         // update Opportunity 's custom field Update_Due_Date_of_Task__c
        opportunity[] optyObj = [select Id,Update_Due_Date_of_Task__c from opportunity where Id =: whatIDs LIMIT 1];
        if(optyObj.size() > 0){
        optyObj[0].Update_Due_Date_of_Task__c = lastUpdatedDate;
        }
        update optyObj;
    }
}


                                

Comments

Popular posts from this blog

Test-Driven Development in Salesforce

Setting a default 'From' address when sending an email from Cases

Email Messaging from Salesforce