User Story
As a Salesforce administrator, I want to ensure that the Last Contact Date field on an account is updated every time a new contact is added or an existing contact is updated. To achieve this, I created a trigger that fires after a contact is inserted or updated. In the trigger, I loop through the list of new or updated contacts and check if they are associated with an account. If a contact is associated with an account, I create a new Account object with the Last Contact Date field set to today's date, and add it to a list of accounts to be updated. Finally, I update all the accounts in the list with a single DML call. With this trigger in place, I can ensure that the Last Contact Date field on an account is always up-to-date, which will help me better track and manage my customer relationships.
Code
Apex Trigger
trigger ContactTrigger on Contact (after insert, after update) {
List<Account> accountsToUpdate = new List<Account>();
for(Contact con : Trigger.new) {
if(con.AccountId != null) {
accountsToUpdate.add(new Account(Id = con.AccountId, Last_Contact_Date__c = Date.today()));
}
}
update accountsToUpdate;
}