Scenario 2: You need to update a custom field on the Contact object, ‘LastCaseDate’, with the date of the most recent related Case. How would you write this trigger?
This would be an ‘after insert’ and ‘after update’ trigger on the Case object. The trigger would gather Contact IDs from the Cases, find the most recent Case date for each Contact, and update the ‘LastCaseDate’ field on the Contact records.
trigger UpdateLastCaseDate on Case (after insert, after update) {
Set<Id> contactIds = new Set<Id>();
for(Case cs : Trigger.new){
if(cs.ContactId != null){
contactIds.add(cs.ContactId);
}
}
Map<Id, Date> contactLastCaseDate = new Map<Id, Date>();
for(AggregateResult ar : [SELECT ContactId, MAX(CreatedDate) lastDate FROM Case WHERE ContactId IN :contactIds GROUP BY ContactId]){
contactLastCaseDate.put((Id)ar.get(‘ContactId’), (Date)ar.get(‘lastDate’));
}
List<Contact> contactsToUpdate = new List<Contact>();
for(Id contactId : contactIds){
contactsToUpdate.add(new Contact(Id = contactId, LastCaseDate__c = contactLastCaseDate.get(contactId)));
}
update contactsToUpdate;
}