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

How to update the OpportunityLineItem using trigger

i created 2 Picklist  fields in opportunity object. i.e servicetype__c and Tier_Level__c.


                ServiceType field contain values i.e  National and International

                TierLevel field contain values i.e  Tier1 and Tier2

i created Price book in Pricebook2 object  after i created multiple products for each price book. 


  ex: pricebook  like Tier1,Tier2..................

        Products like  NationalProduct,Internation Product..................


Now i fills the Opportunity object.  automatically  Product will be added for that opportunity using trigger. the trigger work like this . fetch the servicetype and tierlevel from opportunity then map in pricebook2 and product2 object after automatically added the product for opportunity this is working fine. Here i am  utilclass and trigger.


but Now i need to once Opportunity is updated based selected TierLevel field old product will be removed and new product will be added based on selected value from TierLevel field in Opportuinty object. how can i solve this problem. pls help me.................




trigger OpportunityProduct on Opportunity (after insert, after update) {  

       List<OpportunityLineItem> OLI = new List<OpportunityLineItem>();
        Map<String,String> SMap = OpportunityUtils.ServiceMap();
        Map<String,Id> PBookMap = OpportunityUtils.PricebookMap();
        Map<String,Id> PrMap = OpportunityUtils.ProductMap();
        String strPCode = '';
        String strPBId = '';
     for(Opportunity o:Trigger.New){
            OpportunityLineItem OLIObj = new OpportunityLineItem();
            strPCode = SMap.get(o.Service_Type__c) +Integer.ValueOf(o.Contract_Length_Months__c);
            strPCode = PrMap.get(strPCode);
            strPBId  = PBookMap.get(o.Tier_Level__c);
            List<PriceBookEntry> PBE = [select id, UnitPrice from PriceBookEntry where Product2Id =: strPCode and  Pricebook2Id =: strPBId limit 1];
             if(!PBE.isEmpty()) {
                 OLIObj.PriceBookEntryId = PBE[0].Id;
                 OLIObj.OpportunityId = o.Id;
                 OLIObj.Quantity = 1;
                 OLIObj.TotalPrice = PBE[0].UnitPrice;
         if(!OLI.isEmpty()) {
             insert OLI;
    } //End of Trigger.isInsert



how can i solve this problem. pls help me.................