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
DbjensenDbjensen 

Help populating a long text field with multiple record names

Hello - I have a long text field on an opportunity that I would like to auto populate with the names of the products associated to that opportunity. I'm using a before update trigger and class. I have a map that holds all of the product names and can see the results in a debug statement. However, when I update the field, it's not adding all of the product names in the map. It only adds one name. 

Example: My opp has 2 products. Widget 1 and Widget 2. I need to add both product names to a long text field. Below is my code. Any help would be appreciated. 

public class AddProductNamesToOpportunity {
    
    public static void addProductNmsToOpp(List<Opportunity> newOpp, List<Opportunity> oldOpp) {
        
        string separator = '; ';
        list<Opportunity> oppList = new list<Opportunity>();
        
        //Old Opportunity Maps
        map<Id, Decimal> mapOfOldOpps = new map<Id, Decimal>();
        
        for(Opportunity oldOpps : oldOpp) {
            mapOfOldOpps.put(oldOpps.Id, oldOpps.Amount);
        }
        
        system.debug('values in old map ' +mapOfOldOpps);
        
        //New Opportunity Maps
        map<Id, Decimal> mapOfnewOpps = new map<Id, Decimal>();
        
        for(Opportunity newOpps : newOpp) {
            mapOfnewOpps.put(newOpps.Id, newOpps.Amount);
        }
        
        system.debug('values in new map ' +mapOfnewOpps);
        
        //Query Opp Line Items
        List<OpportunityLineItem> oppLinImList = [SELECT 
                                                  //Id,Product2.Name,PricebookEntry.Product2.Name,
                                                  OpportunityId,Product_Name__c FROM OpportunityLineItem WHERE OpportunityId IN :mapOfnewOpps.keyset()];
        
        system.debug('opp line items found ' +oppLinImList);
        
        //Opp Line Item Maps
        map<Id, String> mapOLI = new map<Id, String>();
        
        for(OpportunityLineItem oli : oppLinImList) {
            mapOLI.put(oli.OpportunityId, oli.Product_Name__c);
        }
        
        system.debug('values in opp line item map' +mapOLI);
        
        for(Opportunity opp : newOpp) {
            if(mapOfOldOpps.values() != mapOfnewOpps.values() && !oppLinImList.isEmpty()) {
                opp.Products_2__c = mapOLI.get(opp.Id);
                oppList.add(opp);
            } else if (oppLinImList.isEmpty()){
                opp.Products_2__c = null;
                oppList.add(opp);
            }
        }
        
        try{
            update oppList;
        } catch (Exception e) {
            system.debug('Opp product field did not update ' +e);
        } 
    }
}