I need to update a custom field (Next_Activity_Date__c) on Opportunity with next closest Date from Event or Task which is added to current Opportunity.
Example: When a user has logged a Task/Event, and it's related to Opportunity - then get closest ActivityDate from OpenActivities and set it to Opportunity.Next_Activity_Date__c
This SOQL request can get all OpenActivities from current Oportunity
Opportunity oppActivities = [SELECT (SELECT ActivityDate FROM OpenActivities ORDER BY ActivityDate ASC) FROM Opportunity WHERE id = :oppId];
How to implement this by not writing two similar triggers on Task & Event objects?
trigger EventTrigger on Event (after insert, after update) {
Opportunity[] oppToUpdate = new Opportunity[]{};
if(Trigger.isInsert || Trigger.isUpdate) {
for(Event e : Trigger.new) {
if(e.WhatId != null && e.WhatId .getSobjectType().getDescribe().getName() == 'Opportunity') {
Opportunity opp = OpportunityHelper.getOpenActivities(e.WhatId);
if(opp.OpenActivities.size() > 0) {
opp.Next_Activity_Date__c = opp.OpenActivities.get(0).ActivityDate;
} else {
opp.Next_Activity_Date__c = null;
}
oppToUpdate.add(opp);
}
}
}
if(oppToUpdate.size() > 0) {
update oppToUpdate;
}
}