function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ColaCola 

Apex Trigger to Update Account field Based on Contact Activity

I'm trying to create a trigger that will update a custom Account field called "In Touch Date" based on the Activity History of the account. I want the "In Touch Date" to always be the most recent date any contact in that account has been in touch. I was able to sucessfully create this trigger on a Contact level so that a Contact field also called "In Touch Date" will update based on the most recent Activity Date (code seen below). I am trying to figure out the easiest way to replicate this trigger on an Account level.

The working trigger on the Contact level is here: 
trigger UpdateInTouchDate on Task (after insert, after update) {
	Set<String> whoIds = new Set<String>();
	
    for (Task t : Trigger.new) {
  		whoIds.add(t.WhoId);
	}
	
   	List<Contact> cons = [SELECT Id, In_Touch_Date__c FROM Contact WHERE Id =: whoIds];
    
   	Map<String, Task> taskMap = new Map<String, Task>();
	
    for (Task t : Trigger.new){
    	if (!(t.Type.equals('Eloqua Activity'))) {
    		if (t.Status.equals('Completed')) {
    			taskMap.put(t.WhoId, t);
    		}
    	}
  		
	}
         
    for (Contact c : cons) {
  		if (taskMap.containsKey(c.Id)) {
    		c.In_Touch_Date__c = taskMap.get(c.Id).ActivityDate;
    		c.POC_Communications__c = 'Muted';
  		}
	}
	update cons;

}

Any suggestions on how to replicate this on an Account level would be much appreciated.
Best Answer chosen by Cola
ColaCola
Resolved this via the following thread: https://developer.salesforce.com/forums/ForumsMain?id=906F0000000AdBxIAK

All Answers

pconpcon
I think you want to do the same code (you could honestly inter-weave it in) but on the WhatId instead of the WhoId.  Gather up your WhatIds, query the account object, and then set the tasks ActivitiyDate the same way you are on line 23.
ColaCola
Resolved this via the following thread: https://developer.salesforce.com/forums/ForumsMain?id=906F0000000AdBxIAK
This was selected as the best answer
Sumanta SatpathySumanta Satpathy
Hi Cola
Can just post the exact code which worked for you. It will be very helpful.

Thanks