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
Ankit SatnalikaAnkit Satnalika 

I Want Trigger to update description field in Account with associated contacts name

I need to update description field in Account object with associated contact names. When these contacts are updated the description field in Account should get updated with the names of the associated contacts with that account.
For Eg : if account has two contacts 1. xyz 2. abc then if either of the contact is updated the description field in Account object should be populated with : xyzabc

Below is the code written system.debug(acc.description) is giving correct result but the same is not populating the description field in Account object.
User-added image
Please help and let me know the error.
Maharajan CMaharajan C
Hi Ankit,

You can use the below trigger:

trigger UpdateCntNameinAccDesc on Contact (after insert,before update) {
    
    List<Account> accListtoUpdate = new List<Account>();
    Set<Id> accIdSet = new Set<Id>();
    for(Contact con : Trigger.New)
    {
        accIdSet.add(con.AccountId);
    }
    
    if(!accIdSet.isEmpty())
    {
        for(Account acc : [Select id, name, Description, 
                           (Select Id, name From Contacts) 
                           From Account Where Id In : accIdSet])
        {
            List<String> templstSrting = new List<String>();
            for(Contact con : acc.contacts)
            {
                templstSrting.add(con.name);
            }
            acc.Description = String.join(templstSrting, '');
            accListtoUpdate.add(acc);
        }    
    }
    
    if(!accListtoUpdate.isEmpty())
    update accListtoUpdate;
}

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
Maharajan.C
Ankit SatnalikaAnkit Satnalika
Thanks :)