+ Start a Discussion

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!!!!
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){
      String subQuery = 'SELECT Lastname FROM Contacts';
          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;

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-:

Hope this helpful !!!