You need to sign in to do that
Don't have an account?

Concatenate String Within For Loop
I am trying to create a trigger that will update an opportunity field called "Tinderbox_Sites__c" after a child object called "Site__c" is inserted with a list of all the child Site names. I have created the below trigger and helper class method but for some reason, when there are multiple child sites, the string will just overwrite instead of concatenate the site names. For example,
Opportunity A has two child Site__c objects:
- Site 1
- Site 2
The "Tinderbox_Sites__c" opportunity field will only display
"Site 2<br />"
instead of the expected concatenated string of sites
"Site 1<br />Site 2<br />"
. Can anyone help me figure out why the string is overwriting instead of concatenating? Thanks!
trigger SiteTrigger on Site__c (after insert) { SiteTriggerHelper helper = new SiteTriggerHelper(); if(Trigger.isAfter && Trigger.isInsert){ helper.updateTinderboxSites(Trigger.new); } }
public void updateTinderboxSites(List<Site__c> sites){ Set<Id> opportunityIds = new Set<Id>(); for(Site__c s: sites){ opportunityIds.add(s.Opportunity__c); } List<Opportunity> opps = new List<Opportunity>([select Id, Tinderbox_Sites__c from Opportunity where Id in : opportunityIds]); List<Opportunity> oppsToUpdate = new List<Opportunity>(); for(Opportunity o: opps){ String html = ''; for(Site__c oppSite: sites){ html += oppSite.Name+'<br />'; } o.Tinderbox_Sites__c = html; oppsToUpdate.add(o); } update oppsToUpdate; }
Trigger.new probably only contains one of the sites. You need to get the rest of them from the database and map them to the opportunites. Try this
All Answers
Trigger.new probably only contains one of the sites. You need to get the rest of them from the database and map them to the opportunites. Try this
This is the simplest trigger for your requirement