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
LightsLights 

Apex: new Product is being added to a different opportunity and not to the opportunity that is being edited

Not a duplicate question guys. Different aspect of the code.

Goal of the code:
Auto add product B once product A is added to the opportunity

Issue:
Adding product B to a different opportunity and not to the opportunity that product A is being added to.

Any idea why? or what part of the code that I should focus on to test different solutions?

Code:
trigger NOVEMBER1 on OpportunityLineItem (after insert, after update)
    {
        List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
    
        List<String> lstProductCodes = new List<String>();
     
        for(OpportunityLineItem optLineItem: Trigger.new)
        {
            if(optLineItem.ProductCode == '00002a')
            {
                lstProductCodes.add(optLineItem.ProductCode);
            }
        }
     
        if(lstProductCodes.size()>0)
        {
            System.debug('lstProductCodes=' + lstProductCodes);
     
            //retrieve the values based on Product list
            List<OpportunityLineItem> lstOpptyLineItems = [SELECT Opportunity.Pricebook2Id, Name, ProductCode , PricebookEntryId, Quantity, UnitPrice
                                                            FROM    OpportunityLineItem
                                                            WHERE ProductCode IN:lstProductCodes];
     
            //create a map which contains Product Name and OpportunityLineItem
            Map<String, OpportunityLineItem> mapOpptyLineItem = new Map<String, OpportunityLineItem>();
            for(OpportunityLineItem item:lstOpptyLineItems)
            {
                mapOpptyLineItem.put(item.ProductCode, item);
            }
     
     
            Id pbkId = lstOpptyLineItems[0].Opportunity.Pricebook2Id;
     
            //retrieve PriceBookEntry of the Product B, this is most important
            PricebookEntry pbeProduct2 = [SELECT Id, Pricebook2Id, UnitPrice, Name, Fee_Percentage_Entry__c 
                                            FROM PricebookEntry
                                            WHERE Name ='Car Oil Fee'
                                            AND Pricebook2Id  IN (SELECT Id FROM PriceBook2 WHERE Id ='01sA00000004lbRIAQ')
                                            LIMIT 1];
     
     
            //retrieve Product A item from the map.        
            OpportunityLineItem itemProductA = mapOpptyLineItem.get('00002a');
            System.debug('itemProductA= ' + itemProductA);
     
            if(itemProductA != null)
            {
                if(Trigger.isInsert)
                {
                //now assign Product A items as required, you can retrieve the amount from Product A
                oliList.add(new OpportunityLineItem(
                    OpportunityId = itemProductA.OpportunityId,
                    PricebookEntryId = pbeProduct2.Id,
                    Quantity = itemProductA.Quantity,
                    UnitPrice = itemProductA.UnitPrice * pbeProduct2.Fee_Percentage_Entry__c * 0.01 )
                  );
                System.debug('oliList=' + oliList);
                insert oliList;
            }
            else if (Trigger.isUpdate)
                {
                    //if you need to update PriceBookEntry of Product B
                    pbeProduct2.UnitPrice = itemProductA.UnitPrice * pbeProduct2.Fee_Percentage_Entry__c * 0.01 ;
                    update pbeProduct2;
     
                    //if you need to update OpportunityLineItem of Product B
                    OpportunityLineItem optLIProductB = [SELECT OpportunityId, Opportunity.Pricebook2Id,
                                                            Name, ProductCode , PricebookEntryId,
                                                            Quantity, UnitPrice
                                                            FROM    OpportunityLineItem
                                                            WHERE ProductCode = '00002b'];
     
                    optLIProductB.Quantity = mapOpptyLineItem.get('00002a').Quantity;
                    optLIProductB.UnitPrice = mapOpptyLineItem.get('00002a').UnitPrice * pbeProduct2.Fee_Percentage_Entry__c * 0.01 ;
     
                    update optLIProductB;
                }
        }
    }
    }

 
Best Answer chosen by Lights
Neetu_BansalNeetu_Bansal
Hello,

Please try the below code:
trigger NOVEMBER2 on OpportunityLineItem( after insert, after update )
{
    List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
    Set<Id> opptyIds = new Set<Id>();
 
    for( OpportunityLineItem optLineItem: trigger.new )
    {
        if( optLineItem.ProductCode == '00002a' )
        {
            opptyIds.add( optLineItem.OpportunityId );
        }
    }
 
    if( opptyIds.size() > 0 )
    {
        //retrieve the values based on Product list
        List<OpportunityLineItem> lstOpptyLineItems = [ SELECT Opportunity.Pricebook2Id, OpportunityId, Name, ProductCode,
                                                        PricebookEntryId, Quantity, UnitPrice
                                                        FROM OpportunityLineItem
                                                        WHERE OpportunityId IN: opptyIds order by ProductCode ];
 
        Map<Id, List<OpportunityLineItem>> mapOpptyLineItem = new Map<Id, List<OpportunityLineItem>>();
        for( OpportunityLineItem item : lstOpptyLineItems )
        {
            List<OpportunityLineItem> oliList1 = new List<OpportunityLineItem>();
            if( mapOpptyLineItem.containsKey( item.OpportunityId ))
            {
                oliList1 = mapOpptyLineItem.get( item.OpportunityId );
            }
            
            oliList1.add( item );
            mapOpptyLineItem.put( item.OpportunityId, oliList1 );
        }
 
 
        //retrieve PriceBookEntry of the Product B, this is most important
        PricebookEntry pbeProduct2 = [ SELECT Id, Pricebook2Id, UnitPrice, Name, Pass_Through_Percentage_Entry__c
                                        FROM PricebookEntry
                                        WHERE Name ='Car Oil Fee'
                                        AND Pricebook2Id  IN (SELECT Id FROM PriceBook2 WHERE Id ='01sA00000004lbRIAQ')
                                        LIMIT 1 ];
 
         if( trigger.isInsert )
         {
             for( Id oppId : mapOpptyLineItem.keySet() )
             {
                 for( OpportunityLineItem item : mapOpptyLineItem.get( oppId ))
                 {
                     if( item.ProductCode == '00002a' )
                     {
                         oliList.add( new OpportunityLineItem(
                                            OpportunityId = oppId,
                                            PricebookEntryId = pbeProduct2.Id,
                                            Quantity = item.Quantity,
                                            UnitPrice = item.UnitPrice * pbeProduct2.Pass_Through_Percentage_Entry__c * 0.01 )
                                          );
                     }
                 }
             }
             
             if( oliList.size() > 0 )
                 insert oliList;
         }
         else if( trigger.isUpdate )
         {
             for( Id oppId : mapOpptyLineItem.keySet() )
             {
                 OpportunityLineItem itemProductA = new OpportunityLineItem();
                 for( OpportunityLineItem item : mapOpptyLineItem.get( oppId ))
                 {
                     if( item.ProductCode == '00002a' )
                     {
                         itemProductA = item;
                         continue;
                     }
                     if( item.ProductCode == '00002b' )
                     {
                         oliList.add( new OpportunityLineItem( Id = item.Id,
                                            OpportunityId = oppId,
                                            PricebookEntryId = pbeProduct2.Id,
                                            Quantity = itemProductA.Quantity,
                                            UnitPrice = itemProductA.UnitPrice * pbeProduct2.Pass_Through_Percentage_Entry__c * 0.01 )
                                          );
                     }
                 }
             }
             
             if( oliList.size() > 0 )
                 update oliList;
         }
    }
}
Let me know if there is any issue and if it helps, please mark it as a best answer.

Thanks,
Neetu

All Answers

Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
are there two Opplineitems with same product code ? that might be the case, please check once.
LightsLights
I don't think the product code would do that.
LightsLights
I just need to find a way to tell the code to add the new opportunitylineitem to the current opportunity
Neetu_BansalNeetu_Bansal
Hello,

Please try the below code:
trigger NOVEMBER2 on OpportunityLineItem( after insert, after update )
{
    List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
    Set<Id> opptyIds = new Set<Id>();
 
    for( OpportunityLineItem optLineItem: trigger.new )
    {
        if( optLineItem.ProductCode == '00002a' )
        {
            opptyIds.add( optLineItem.OpportunityId );
        }
    }
 
    if( opptyIds.size() > 0 )
    {
        //retrieve the values based on Product list
        List<OpportunityLineItem> lstOpptyLineItems = [ SELECT Opportunity.Pricebook2Id, OpportunityId, Name, ProductCode,
                                                        PricebookEntryId, Quantity, UnitPrice
                                                        FROM OpportunityLineItem
                                                        WHERE OpportunityId IN: opptyIds order by ProductCode ];
 
        Map<Id, List<OpportunityLineItem>> mapOpptyLineItem = new Map<Id, List<OpportunityLineItem>>();
        for( OpportunityLineItem item : lstOpptyLineItems )
        {
            List<OpportunityLineItem> oliList1 = new List<OpportunityLineItem>();
            if( mapOpptyLineItem.containsKey( item.OpportunityId ))
            {
                oliList1 = mapOpptyLineItem.get( item.OpportunityId );
            }
            
            oliList1.add( item );
            mapOpptyLineItem.put( item.OpportunityId, oliList1 );
        }
 
 
        //retrieve PriceBookEntry of the Product B, this is most important
        PricebookEntry pbeProduct2 = [ SELECT Id, Pricebook2Id, UnitPrice, Name, Pass_Through_Percentage_Entry__c
                                        FROM PricebookEntry
                                        WHERE Name ='Car Oil Fee'
                                        AND Pricebook2Id  IN (SELECT Id FROM PriceBook2 WHERE Id ='01sA00000004lbRIAQ')
                                        LIMIT 1 ];
 
         if( trigger.isInsert )
         {
             for( Id oppId : mapOpptyLineItem.keySet() )
             {
                 for( OpportunityLineItem item : mapOpptyLineItem.get( oppId ))
                 {
                     if( item.ProductCode == '00002a' )
                     {
                         oliList.add( new OpportunityLineItem(
                                            OpportunityId = oppId,
                                            PricebookEntryId = pbeProduct2.Id,
                                            Quantity = item.Quantity,
                                            UnitPrice = item.UnitPrice * pbeProduct2.Pass_Through_Percentage_Entry__c * 0.01 )
                                          );
                     }
                 }
             }
             
             if( oliList.size() > 0 )
                 insert oliList;
         }
         else if( trigger.isUpdate )
         {
             for( Id oppId : mapOpptyLineItem.keySet() )
             {
                 OpportunityLineItem itemProductA = new OpportunityLineItem();
                 for( OpportunityLineItem item : mapOpptyLineItem.get( oppId ))
                 {
                     if( item.ProductCode == '00002a' )
                     {
                         itemProductA = item;
                         continue;
                     }
                     if( item.ProductCode == '00002b' )
                     {
                         oliList.add( new OpportunityLineItem( Id = item.Id,
                                            OpportunityId = oppId,
                                            PricebookEntryId = pbeProduct2.Id,
                                            Quantity = itemProductA.Quantity,
                                            UnitPrice = itemProductA.UnitPrice * pbeProduct2.Pass_Through_Percentage_Entry__c * 0.01 )
                                          );
                     }
                 }
             }
             
             if( oliList.size() > 0 )
                 update oliList;
         }
    }
}
Let me know if there is any issue and if it helps, please mark it as a best answer.

Thanks,
Neetu
This was selected as the best answer
LightsLights
@Neetu_Bansal You're the best! Thank you!