[SalesForce] how to add child record fields into a single field in Parent object using trigger

I have two objects Child__c and Parent__c with master detail relationship. so when a record is inserted or updated I want add Field1__c and Field2__c to the Parent custom field concatenate__c with comma seperated(field1__c,Field2__c).

If there are multiple child records I want to seperate them with ':'
for example :field1__c,Field2__c:field1__c,Field2__c….

I tried the below code but when an update is made it is updating with new value

Trigger:

trigger updateVals on Child_object__c (after Insert, after Update) 
{

    List<Parent_object__c> poList = new List<Parent_object__c>();
    Set<Id> Po_Ids= new Set<Id>();

    for (Child_object__c childObj : Trigger.new ){
        Po_Ids.add(childObj.ParentLookup__c);
    }

    if(Trigger.IsInsert||Trigger.IsUpdate){
        List<Parent_object__c> po=[Select Id,concatenate__c from Parent_object__c where ID IN: Po_Ids]; 

        for(Parent_object__c p : po){
            for (Child_object__c c: Trigger.new){
                p.concatenate__c = c.field1__c +','+ c.fiedl2__c;
                poList.add(p);

            }
        }

        update poList ;
    }    
}

Best Answer

The latest value is updated in the parent because you are not concatenatine the value of concatenate__c in parent record, you are replacing it. Also you are not fetching the other child records present under the parent

  1. Query all the parents records and Child records associated with the parents for which the childs are edited.
  2. Create a string and concatenate the values for child fields.
  3. Assign this value to parent field.
  4. Update the parent record.

    trigger updateVals on Child_object__c(after Insert, after Update) {
    
    List < Parent_object__c > poList = new List < Parent_object__c > ();
    Set < Id > Po_Ids = new Set < Id > ();
    
    for (Child_object__c childObj: Trigger.new) {
        Po_Ids.add(childObj.ParentLookup__c);
    }
    
    
    if (Trigger.IsInsert || Trigger.IsUpdate) {
        List < Parent__c > po = [Select Id, Concatenate__c, (Select field1, field2 from Child__r) from Parent__c where Id IN: Po_Ids];
        for (Parent_object__c p: po) {
            String concatenateString = '';
            for (Child_object__c c: p.Child__r) {
                concatenateString += c.field1__c + ',' + c.fiedl2__c + ' : ';
    
            }
            p.Concatenate__c = concatenateString;
            poList.add(p);
        }
    
    
        update poList;
    
    }
    
    }