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 parentUpdate the parent record.