[SalesForce] Trigger to copy child object picklist values to parent object separated by comma

I have picklist field "Location" on opportunity object and text field "Type" on Account object. I want to copy the picklist values from all opportunities related to the account and display it on "Type" field on account separated by comma. I tried using process builder but didn't work, tried using below trigger but not working, any help?

trigger UpdateAmount on Opportunity (after insert, after update) {
Map parentOpps = new Map();
Set listIds = new Set();

for (Opportunity childObj : Trigger.new) {
listIds.add(childObj.AccountId);
}

parentOpps = new Map([SELECT id, Opp_Location__c ,
(SELECT ID,Location_Type__c FROM Opportunities)
FROM Account WHERE ID IN :listIds]);

List lstAccount = new List();

for(Account acct:parentOpps.values())
{
List strType = new List();
for(Opportunity oppty:acct.Opportunities)
{
strType.add(oppty.Opp_Location__c);
}
acct.Location_Type__c = String.join(strType,',');

}

update parentOpps.values();
}

Best Answer

The code you have shared will not at all compile.

  • use close brace here for (Opportunity childObj : Trigger.new)
  • use childObj.AccountId instead of childObj.Account to access AccountId
  • When you use relationship query be sure to use Opportunities instead of Opportunity.
  • You should put Opportunity's Opp_Location__c into a List. Then use String.join() to add those with comma delimited.
  • And finally update accounts.

Trigger

trigger UpdateAmount on Opportunity (after insert, after update) { 
  Map<ID, Account > parentOpps = new Map<ID, Account>(); 
  Set<Id> listIds = new Set<Id>();

  for (Opportunity childObj : Trigger.new) {
    listIds.add(childObj.AccountId);
  }

  parentOpps = new Map<Id, Account>([SELECT id, Location_Type__c ,
                                        (SELECT ID, Opp_Location__c  FROM Opportunities) 
                                    FROM Account WHERE ID IN :listIds]);

  List<Account> lstAccount = new List<Account>();

  for(Account acct:parentOpps.values())
  {  
      List<String> strType = new List<String>();
      for(Opportunity oppty:acct.Opportunities)
      {
          strType.add(oppty.Opp_Location__c);
      }
      acct.Location_Type__c = String.join(strType,',');

  }

  update parentOpps.values();
}
Related Topic