function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Copy product name in account custom field

I am using the following code to copy all the opportunity products of an Account in a custom text field in Account object.

Now i am trying to use a small logic. that is 

if there is more than one opportunity product associated to the account then don't copy all the names 

just assign a text 'Academic' to custom text field.

if there is only one product assigned then then copy the opportunity product nam.



trigger MyAccountTrigger1 on Account(before update, before insert) {

Map<ID,Set<String>> aIdToUniqueProductSetMap = new Map<ID,Set<String>> ();
Set<String> uniqueProdSet= new Set<String>();

// Go through each Oppo and collect a unique set of Product names from all OLI
for (Opportunity o : [select id, accountId,
(select id, PricebookEntry.Product2.Name from OpportunityLineItems)
from Opportunity where accountId IN] ) {
Set<String> productsInOppoSet = new Set<String> ();
//reset our set for this Oppo
for (OpportunityLineItem oli : o.opportunityLineItems)
// With the unique set, add it into our Map associating each account to its unique product set
if (aIdToUniqueProductSetMap.containsKey(o.accountId)) {
uniqueProdSet = aIdToUniqueProductSetMap.get(o.accountId); // add this Oppo's unique set to whatever we have so far
aIdToUniqueProductSetMap.put(o.accountId,uniqueProdSet); // put it back in the Map
aIdToUniqueProductSetMap.put(o.accountId,productsInOppoSet); // first Oppo for this Account; simply do a put


for(Account a:
// All done with Oppos, now put back into each triggered Account
for (Account a:

if (aIdToUniqueProductSetMap.containsKey( { // only for those Accounts that had Oppos with products
String concatenatedProducts = '';
for (String p : aIdToUniqueProductSetMap.get(
concatenatedProducts = concatenatedProducts + (concatenatedProducts.length() == 0 ? '' : ' ') + p; // separate with spaces; other delims possible
a.ProductNameCopy__c = concatenatedProducts ; // when the trigger completes, the triggered Accounts get updated


can anyone advise?