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
jai.sjai.s 

Is it possible to create a trigger to update Parent field in comma separated format?

I have two objects Parent(Account) and Child(Contact). I want to update all associated child records 'Last Name' with comma separated formate in parent filed (custome field).

For suppose i have five child records for associate parent record, now i want to update this five child records last names into that parent filed with comma separated.

I know we can do this using VF and Apex. Can you please clarify is it possible through Triggers? And if u can please share sample code.

Thanks in advance!!!!
lkatneylkatney
Hey ,

You can easily do it through following trigger:

trigger CopyChildNames on Contact(after insert, after update, before delete){

     List<String> accountsLst = new List<String>();
     List<String> accountsToUpdate= new List<String>();
     List<String> excludedContacts = new List<String>();

      for(contact con : trigger.new){
            accountsLst.add(con.accountId);
           if(trigger.isDelete){
              excludedContacts.add(con.id);
           }
      }
     
      String subQuery = 'SELECT Lastname FROM Contacts';
      if(trigger.isDelete){
          subQuery = ' Id NOT IN excludedContacts';
      }
      String query = 'SELECT Id, Name , Custom_field__c, (' + subQuery + ') FROM Account WHERE Id IN accountLst'      
      for(Account acc : Database.Query(query)){
            string lastnameValues = '';
            for(Contact relatedCon : acc.Contacts){
                 lastnameValues += String.isBlank(lastnameValues) ? con.lastname : ',' + con.lastname;
            }
            acc.Custom_field__c = lastnameValues;
            accountsToUpdate.add(acc);
      }
}

Hope this helps!!
Sumit Saini 1Sumit Saini 1
Hi All,

Now we can populate child records field value on parent record in comma seperate by using apex trigger.

Please see my post-:
https://sfdctechsolutions.blogspot.com/2021/10/populate-child-records-field-value-on.html

Hope this helpful !!!