You need to sign in to do that
Don't have an account?
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 :Trigger.new] ) {
Set<String> productsInOppoSet = new Set<String> ();
//reset our set for this Oppo
for (OpportunityLineItem oli : o.opportunityLineItems)
productsInOppoSet.add(oli.PricebookEntry.Product2.Name);
// 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
uniqueProdSet.addAll(productsInOppoSet);
aIdToUniqueProductSetMap.put(o.accountId,uniqueProdSet); // put it back in the Map
}
else
aIdToUniqueProductSetMap.put(o.accountId,productsInOppoSet); // first Oppo for this Account; simply do a put
}
if(uniqueProdSet.size()>1)
{
for(Account a: Trigger.new)
{a.productNameCopy__c='Academic';}
}
else
{
// All done with Oppos, now put back into each triggered Account
for (Account a: Trigger.new)
{
if (aIdToUniqueProductSetMap.containsKey(a.id)) { // only for those Accounts that had Oppos with products
String concatenatedProducts = '';
for (String p : aIdToUniqueProductSetMap.get(a.id))
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?