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
Mattias NordinMattias Nordin 

Trigger to uppdate a field on the account from all related list

Hi,

 

Im thinking of writing a trigger that capture the last modified date of all related list on the account and to store the latest last modified date on the account.

 

What whould be the best method to accomplish this? Create the trigger on the account and get the information from all related items or to create a trigger on each related item?

 

I want the trigger to execute whenever any related item such as an activity or a note has been added.

bob_buzzardbob_buzzard

You'll have to create the trigger on each related item, as account triggers won't fire when a related object is added.

Mattias NordinMattias Nordin

Anyone have an example of how to save a value from the child to the parent?

 

In this case i want to add the last modified date from the contact to the account record when the contact is changed.

 

Any tip to get me started ?

bob_buzzardbob_buzzard

You won't be able to change the last modified date on the account, as that is set by the system when the account is saved.  An example of updating a custom field called "Child_Last_Modified_c" is shown below - caveat emptor, I haven't compiled this :)

 

 

trigger UpdateParentAccount on Contact (after insert, after update) 
{
   Map<Id, Contact> contactsByAccountId=new Map<Id, Contact>();
   for (Contact cont : trigger.new)
   {
       if (null!=cont.accountId)
       {
          contactsByAccountId.put(contact.accountId, contact);
       }
   }

   List<Account> accs=[select id, Contact_Last_Modified__c from Account where id in :contactsByAccountId.keySet()];
   for (Account acc : accs)
   {
      Contact cont=contactsByAccountId.get(acc.id);
      acc.Contact_Last_Modified__c=cont.LastModifiedDate;
   }

   update accs;
}