I need help to get the unique names from the child object records and concatenate them on the text field on the parent object. I was able to concatenate but unable to unique the values. As an example, if there are 4 child records (apple, mango, mango, apple) to the parent record. I want to update as apple; mango on the parent object field.
list<id> parentIDstoUpdate = new list<id>();
if(Trigger.isAfter){
if(Trigger.isInsert || Trigger.isUpdate ){
for (ChildObject__c co : Trigger.new) {
parentIDstoUpdate.add(co.ParentObject__c);
}
}
}
map<id,string> mapParentIdtoString = new Map<ID,String>();
string str;
for (ChildObject__c co: [SELECT Fruit__c, ParentId FROM ChildObject__c WHERE ParentId =:parentIDstoUpdate ]){
if(mapParentIdtoString.containsKey(co.ParentId)){
str = mapParentIdtoString.get(co.ParentId);
str = str + '; ' + co.Fruit__c;
mapParentIdtoString.put(co.ParentId,str);
}else{
mapParentIdtoString.put(co.ParentId,co.Fruit__c);
}
}
list<ParentObject__c> recordstoUpdate = new list<ParentObject__c>();
for (ParentObject__c p: [SELECT ID, Parent_Field__c FROM ParentObject__c WHERE id =:recordstoUpdate ]){
p.Parent_Field__c = mapParentIdtoString.get(p.id);
recordstoUpdate.add(p);
}
if (recordstoUpdate != null && recordstoUpdate.size() >0){
update recordstoUpdate;
}
}