I have picklist field “Opp_Location__c” on opportunity object and text field “Location_Type__c” on Account object. I want to copy the picklist values from all opportunities related to the account and display it on “Location_Type__c” field on account separated by comma.
Trigger UpdateAmount on Opportunity(after update){ Set<id> setAccId = new Set<id>(); Map<ID, Account> mapaccountvalue = new Map<ID, Account>(); for(Opportunity opp: Trigger.New) { if(opp.Opp_Location__c!=null && c.Opp_Location__c!=Trigger.OldMap.get(opp.id).Opp_Location__c && opp.accountid !=null ){ setAccId.add(c.accountid); } } mapaccountvalue = new Map<id,Account> ([select id,Location_Type__c,(SELECT ID, Opp_Location__c FROM Opportunities) from Account where id IN: setAccId]); for(Account acct:mapaccountvalue.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 mapaccountvalue.values; }
Point to Note:
How to join list of strings with a separator using Apex in Salesforce?
join(iterableObj, separator)
Joins the elements of the specified iterable object, such as a List, into a single String separated by the specified separator.
List <String> strList = new List < String > { 'Mango', 'Orange', 'Apple' }; String str = String.join( strList, ', ' ); system.debug( 'Joined with coma is ' + str );
Looping thorugh SOQL Subquery
for ( Account acc: [ SELECT Id, Location_Type__c,(SELECT id,Opp_Location__c FROM Opportunities ) FROM Account ] ) { for ( Opportunity opp : acc.Opportunities ) { }
Reference:
https://salesforce.stackexchange.com/questions/172030/trigger-to-copy-child-object-picklist-values-to-parent-object-separated-by-comma/327526#327526