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
RossGRossG 

too many soql queries error

I'm getting a too many soql queries erros on this line
        oliMgr = new OppLineItemManager(triggerList);
in the following trigger:       
trigger OpportunityLineItemTrigger on OpportunityLineItem (
    before insert, before update, before delete, after insert, after update, after delete
) {
    
    if (!RecursionControl.getSuppressionFlag(RecursionControl.SuppressionFlag.OPPORTUNITY_LINE_ITEM_TRIGGER)) {
    
        // Declare trigger variables
        DeletionValidator oliDeletionValidator;
        OppLineItemManager oliMgr;
        OpportunityLineItem oliOld;
        List<OpportunityLineItem> oliListForRenewedFromInfo = new List<OpportunityLineItem>();
        List<OpportunityLineItem> triggerList;
        Set<Id> contractIdSet = new Set<Id>();
        Set<Id> oppIdSet = new Set<Id>();
        
        // Aggregate trigger list into single variable
        if (Trigger.isInsert || Trigger.isUpdate) {
            triggerList = Trigger.new;
        } else { // Trigger.isDelete
            triggerList = Trigger.old;
        }
        
        // Perform evaluation    
        for (OpportunityLineItem oliNew : triggerList) {
        
            // Reset record-level variables
            oliOld = Trigger.isUpdate ? Trigger.oldMap.get(oliNew.Id) : null;
            
            if (Trigger.isBefore) {
                if ((Trigger.isInsert && oliNew.Renewed_From_Line_Item_Record_Id__c != null) ||
                    (Trigger.isUpdate && oliNew.Renewed_From_Line_Item_Record_Id__c != oliOld.Renewed_From_Line_Item_Record_Id__c)
                ) {
                    oliListForRenewedFromInfo.add(oliNew);
                }
            } else { // Trigger.isAfter           
                if (Trigger.isUpdate) {                        
                    if (oliOld.Contract__c != oliNew.Contract__c || oliOld.Quantity != oliNew.Quantity) {                    
                        if (oliNew.Contract__c != null) { contractIdSet.add(oliNew.Contract__c); }
                        if (oliOld.Contract__c != null) { contractIdSet.add(oliOld.Contract__c); }
                    }                    
                } else { // Trigger.isInsert || Trigger.isDelete                
                    if (oliNew.Contract__c != null) { contractIdSet.add(oliNew.Contract__c); }
                }           
            }
        }
            
        // Perform processing
        oliMgr = new OppLineItemManager(triggerList);        
        if (Trigger.isBefore) {        
            if (Trigger.isInsert) {        
                oliMgr.setContractField();
            }            
            oliMgr.setGeneralLineItemFields();
            if (!oliListForRenewedFromInfo.isEmpty()) {
                OppLineItemManager.setRenewedFromProductCode(oliListForRenewedFromInfo);
            }
            if (Trigger.isDelete) {
                oliDeletionValidator = new DeletionValidator(triggerList,DeletionValidator.ValidationType.LINE_ITEM);
                oliDeletionValidator.validateDeletion();
            }
        } else if (Trigger.isAfter) {
            oliMgr.setParentOppRollupFields();
        }
        if (!contractIdSet.isEmpty()) {
            OppLineItemManager.setSKPFieldOnContract(contractIdSet);
        }
        
        
        /* Code from Apex Trigger "CeligoTrigger_OpportunityLineItem", which was deactivated
         * in order to be consolidated here
         */
        //context check
        if(Trigger.size<0)return;
        
        if(Trigger.isBefore && Trigger.isInsert){
            new CeligoTrigger_OpportunityLineItem(Trigger.new,Trigger.old, CeligoTrigger.TriggerType.BeforeInsert).doTrigger();
        //context check
        }else if(Trigger.isAfter && Trigger.isInsert){
            new CeligoTrigger_OpportunityLineItem(Trigger.new,Trigger.old, CeligoTrigger.TriggerType.AfterInsert).doTrigger();
        }else if(Trigger.isAfter && Trigger.isUpdate){
            new CeligoTrigger_OpportunityLineItem(Trigger.new,Trigger.old, CeligoTrigger.TriggerType.AfterUpdate).doTrigger();
        }else if(Trigger.isAfter && Trigger.isDelete){
            new CeligoTrigger_OpportunityLineItem(Trigger.new,Trigger.old, CeligoTrigger.TriggerType.AfterDelete).doTrigger();
        }
    }
}

Anyone see how I can modify this trigger code to avoid that error?  Nothing I try seems to be working.  Thanks a lot
RamuRamu (Salesforce Developers) 
Probably the utility class OppLineItemManager might be using SOQL statement inside for loop. This could be the only reason why this code is throwing an error. I do not see any other issues with your code.
RossGRossG
Thanks Ramu.  Yeah I'm pasting the utility class below.

The thing is...all this code is in prod and it works.  But when I go in the sandbox and try to add a simple workflow rule with field update on opportunity product object, it throws the too many soql query error on this trigger and utility class.  Do you see anything wrong with the utility class here as far as soql queries in for loops, because I don't see any:
 
public class OppLineItemManager {
    
    
    /* Manage setting fields on line items, and fields on other objects that are dependent on
     * line item data
     */
    
    // Declare static variables
    private static Boolean renewalUpdateIsSuppressed = FALSE;
    private static Map<Id,Boolean> updatedProductMap = new Map<Id,Boolean>();
    private static final Set<String> CREDIT_PRODUCT_CODES = new Set<String>{'Cust-Cred'};
    private static final Set<String> PRODUCT_CODES_REQUIRING_NEGATIVE_PRICING = new Set<String>{'Cust-Cred','Cust-Discount','REF'};
    
    // Declare class variables
    private Boolean triggerContainsPartnerReferralFee = false;
    private Map<Id,Opportunity> oppDetailsMap;
    private Map<Id,OpportunityLineItem> oliDetailsMap = new Map<Id,OpportunityLineItem>();
    private Map<Id,OpportunityLineItem> oliOldDetailsMap = new Map<Id,OpportunityLineItem>();
    private Map<Id,PricebookEntry> pbeDetailsMap = HelperCollection.getAllPricebookEntries();
    private Map<Id,List<OpportunityLineItem>> oppLineItemsMap = new Map<Id,List<OpportunityLineItem>>();
    private Set<Id> oliTriggerIdSet = new Set<Id>();
    
    
    /* Set product map */
    public static void suppressRenewableUpdate() {
        renewalUpdateIsSuppressed = TRUE;
    }


    /* Constructor */
    public OppLineItemManager(List<OpportunityLineItem> oliList) {  
    
        // Perform validation
        if (oliList == null || oliList.isEmpty()) {
            throw new HelperCollection.customException('OppLineItemManager constructor parameter must not be null or empty.');
        }
    
        // Declare method variables
        List<OpportunityLineItem> oliFinalList = new List<OpportunityLineItem>();
        List<OpportunityLineItem> oliTempList;
        Set<Id> oliIdSet = new Set<Id>();
        Set<Id> oppIdSet = new Set<Id>();
        
        // Aggregate data
        for (OpportunityLineItem oli : oliList) {
            oppIdSet.add(oli.OpportunityId);
            if (oli.Id != null) {
                oliTriggerIdSet.add(oli.Id);
            }
            if (pbeDetailsMap.get(oli.PricebookEntryId).ProductCode == 'REF') {
                triggerContainsPartnerReferralFee = true;
            }
        } 

        // Retrieve Opp info
        oppDetailsMap = new Map<Id,Opportunity>([
            SELECT
                Id,
                Auto_generated_Renewal__c,
                Baseline_ARR__c,
                Baseline_MRR__c,
                Baseline_Product_Codes__c,
                CloseDate,
                IsClosed,
                Type,
                (SELECT Id FROM Contract__r WHERE IsDeleted = FALSE),
                (
                    SELECT
                        Id,
                        Item_Annualized_hACV__c,
                        Item_ARR__c,
                        Item_Baseline_ARR__c,
                        Item_Baseline_MRR__c,
                        Item_BLRA__c,
                        Item_Commissionable_hACV__c,
                        Item_Commissionable_hMY__c,
                        Item_Commissionable_hMY_Extension__c,
                        Item_Customer_Credit__c,
                        Item_Hybrid_ACV__c, // "Item hACV"
                        Item_MRR__c,
                        Item_MY_Extension__c, // "Item hMY Extension"
                        Item_Type__c,
                        ListPrice,
                        OpportunityId,
                        PricebookEntryId,
                        PricebookEntry.ProductCode,
                        PricebookEntry.Product2.Price_Book_License__c, // "Product License Type"
                        PricebookEntry.Product2.Renewable__c,
                        PricebookEntry.UnitPrice,
                        Product_License_Type_Picklist__c, // "Product License Type"
                        Quantity,
                        Renewable__c,
                        Reseller_Uplift__c,
                        Term_End_Date__c,
                        Term_Length__c,
                        Term_Start_Date__c,
                        TotalPrice,
                        UnitPrice
                    FROM OpportunityLineItems
                    WHERE IsDeleted = FALSE
                    ORDER BY PricebookEntry.ProductCode
                )
            FROM Opportunity
            WHERE Id IN :oppIdSet
        ]);
        
        // Aggregate existing line item info
        for (Opportunity o : oppDetailsMap.values()) {
            oppLineItemsMap.put(o.Id,new List<OpportunityLineItem>());
            for (OpportunityLineItem oli : o.OpportunityLineItems) {
                oliIdSet.add(oli.Id);
                oliDetailsMap.put(oli.Id,oli);
            }
        }
        oliOldDetailsMap = oliDetailsMap.deepClone();
        
        // Update aggregate collections with trigger line item info
        for (OpportunityLineItem oli : oliList) {
            if (oli.Id != null) {
                if (!renewalUpdateIsSuppressed) {
                    oliDetailsMap.put(oli.Id,oli);
                }
            } else { // oli.Id == null
                oliFinalList.add(oli);
            }
        }
        oliFinalList.addAll(oliDetailsMap.values());
        
        // Map oli info by Opp Id & aggregate pbe Ids
        for (OpportunityLineItem oli : oliFinalList) {
            oliTempList = oppLineItemsMap.get(oli.OpportunityId);
            oliTempList.add(oli);
            oppLineItemsMap.put(oli.OpportunityId,oliTempList);
        }
    }
    
    
    /* Update "Contract" field to point to (one of) the parent Opportunity's Contract record(s) */
    public void setContractField() {
    
        // Declare method variables
        Contract contract;
         
        // Point OLIs to Contracts
        for (Opportunity o : oppDetailsMap.values()) {
            contract = null;
            if (!o.Contract__r.isEmpty() && o.Contract__r.get(0) != null) {
                contract = o.Contract__r.get(0);
                for (OpportunityLineItem oli : oppLineItemsMap.get(o.Id)) {
                    oli.Contract__c = contract.Id;
                }
            }
        }
    }
    
    
    /* Validate and update various line item fields */
    public void setGeneralLineItemFields() {
    
        // Declare method variables
        Decimal amt;
        Decimal creditTotal;
        Decimal itemCommissionableTotalPrice;
        Decimal itemNetTotalPrice;
        Decimal partnerReferralFee;
        Decimal totalPrice;
        OpportunityLineItem oliOld;
        PricebookEntry pbe;
        List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();

        // Perform processing
        for (Opportunity o : oppDetailsMap.values()) {
        
            // Reset opp-level variables
            amt = 0;
            creditTotal = 0;
            partnerReferralFee = 0;
        
            for (OpportunityLineItem oliNew : oppLineItemsMap.get(o.Id)) {

                // Reset line-item-level variables
                oliOld = Trigger.isUpdate ? oliOldDetailsMap.get(oliNew.Id) : null;
                pbe = pbeDetailsMap.get(oliNew.PricebookEntryId);
                totalPrice = HelperCollection.getLineItemPrice(oliNew);
                
                if (!(Trigger.isDelete && oliTriggerIdSet.contains(oliNew.Id))) {

                    // Perform validation
                        // Implementing via Apex rather than via standard Validation Rule because Validation Rule does not seem to function as expected for
                        // the line item price fields (presumably due to order of execution of the hidden out-of-the-box trigger code responsible for
                        // final population of those fields)
    
                    if (PRODUCT_CODES_REQUIRING_NEGATIVE_PRICING.contains(pbe.ProductCode) &&
                        oliNew.UnitPrice >= 0 &&
                        (Trigger.isInsert || (oliOld.UnitPrice != oliNew.UnitPrice) || (oliOld.TotalPrice != totalPrice))
                    ) {
                        oliNew.UnitPrice.addError('\'Sales Price\' must be negative for the \'Cust-Cred\', \'Cust-Discount\', and \'REF\' products since they represent a credit or discount to the customer or a fee paid.  Use the \'-\' symbol to make the \'Sales Price\' number negative.');
                    }
                
                    // Round 1 processing
                    if (!PRODUCT_CODES_REQUIRING_NEGATIVE_PRICING.contains(pbe.ProductCode)) {
                        amt += totalPrice;
                    } else {
                        if (pbe.ProductCode == 'Cust-Cred') {
                            creditTotal += totalPrice;
                        }
                    }
                        // Reduce total price basis by amount of any applied customer credit
                        // Validation ensures credit pricing is negative
                    oliNew.Item_Baseline_MRR__c = oliNew.Item_BLRA__c == null ? null : setMRRValue(oliNew,oliNew.Item_BLRA__c).setScale(2);
                    itemNetTotalPrice = totalPrice + (
                        oliNew.Item_Customer_Credit__c == null ? 0 : oliNew.Item_Customer_Credit__c
                    );                                
                    if (oliNew.Item_Type__c == null) {
                        oliNew.Item_Type__c = 'New';
                    }  
                    if (pbe.ProductCode == 'REF' && !(Trigger.isDelete && oliTriggerIdSet.contains(oliNew.Id))) {
                        partnerReferralFee += totalPrice;
                    }                
                    oliNew.Product_License_Type_Picklist__c = pbe.Product2.Price_Book_License__c;
                    oliNew.Renewable__c = pbe.Product2.Renewable__c;
                    
                    // Round 2 processing
                    oliNew.Item_Baseline_ARR__c = (oliNew.Item_Baseline_MRR__c == null ? null : (12 * oliNew.Item_Baseline_MRR__c).setScale(2)); // Dependent on
                        // "Item Baseline MRR"
                    oliNew.Item_Hybrid_ACV__c = setItemhACV(oliNew,itemNetTotalPrice); // Dependent on "Product License Type"
                    oliNew.Item_MRR__c = setItemMRR(oliNew); // Dependent on "Item Type"
    
                    // Round 3 processing
                    oliNew.Item_Annualized_hACV__c = setItemrenewablehACV(oliNew);
                    oliNew.Item_ARR__c = (oliNew.Item_MRR__c == null ? null : (12 * oliNew.Item_MRR__c).setScale(2)); // Dependent on
                        // "Item MRR"
                    oliNew.Item_Commissionable_hACV__c = setItemCommissionablehACV(oliNew,itemNetTotalPrice); // Default value;
                        // may be reset later to account for any partner referral fees; dependent on "Item hACV"
                    oliNew.Item_MY_Extension__c = setItemhMYExtension(oliNew,itemNetTotalPrice); // Dependent on "Item hACV"
                        
                    // Round 4 processing
                    oliNew.Item_Commissionable_hMY_Extension__c = oliNew.Product_License_Type_Picklist__c == 'Perpetual'
                        ? oliNew.Item_Commissionable_hACV__c
                        : oliNew.Item_MY_Extension__c;
                }
            }
            
            // If there are referral fees, apply them to line items
            if (partnerReferralFee != 0 || triggerContainsPartnerReferralFee) {
            
                for (OpportunityLineItem oliNew : oppLineItemsMap.get(o.Id)) {  
                                  
                    if (!(Trigger.isDelete && oliTriggerIdSet.contains(oliNew.Id))) {

                        if (!PRODUCT_CODES_REQUIRING_NEGATIVE_PRICING.contains(pbeDetailsMap.get(oliNew.PricebookEntryId).ProductCode)) {
                        
                            // Reset line-item-level variables
                            totalPrice = HelperCollection.getLineItemPrice(oliNew);
                            
                            itemNetTotalPrice = totalPrice + (
                                oliNew.Item_Customer_Credit__c == null ? 0 : oliNew.Item_Customer_Credit__c
                            );

                            oliNew.Item_Partner_Referral_Fee__c = 
                                partnerReferralFee == 0 || amt - partnerReferralFee == 0
                                    ? null
                                    : (partnerReferralFee * (itemNetTotalPrice / (amt + creditTotal) )).setScale(2);
                            itemCommissionableTotalPrice = itemNetTotalPrice + (
                                    oliNew.Item_Partner_Referral_Fee__c == null
                                    ? 0
                                    : oliNew.Item_Partner_Referral_Fee__c
                                );
                            oliNew.Item_Commissionable_hACV__c = setItemCommissionablehACV(oliNew,itemCommissionableTotalPrice);
                            
                            oliNew.Item_Commissionable_hMY_Extension__c = oliNew.Product_License_Type_Picklist__c == 'Perpetual'
                                ? setItemhACV(oliNew,itemCommissionableTotalPrice)
                                : setItemhMYExtension(oliNew,itemCommissionableTotalPrice);
                            
                            if (oliNew.Id != null && !oliTriggerIdSet.contains(oliNew.Id)) {
                                oliList.add(oliNew);
                            }
                        }
                    }
                }
            }
        }        
        if (!oliList.isEmpty()) { // Update line items that aren't part of original trigger
            RecursionControl.setSuppressionFlag(RecursionControl.SuppressionFlag.OPPORTUNITY_LINE_ITEM_TRIGGER,true);
            update oliList;
            RecursionControl.setSuppressionFlag(RecursionControl.SuppressionFlag.OPPORTUNITY_LINE_ITEM_TRIGGER,false);
        }
    }
    
        
    /* Calculate value of "Item Annualized hACV" field */
    private Decimal setItemrenewablehACV(OpportunityLineItem oli) {
        
        // Declare method variables
        Decimal itemrenewablehACV = oli.Item_Hybrid_ACV__c;
        
        if (oli.Item_Hybrid_ACV__c != null &&
            oli.Product_License_Type_Picklist__c != 'Perpetual' &&
            (
                oli.Term_End_Date__c < oli.Term_Start_Date__c.addYears(1).addDays(-1) ||
                oli.Product_License_Type_Picklist__c == 'Services'
            )
        ) {
            itemrenewablehACV = (setMRRValue(oli,oli.Item_Hybrid_ACV__c) * 12).setScale(2);
        }
        
        return itemrenewablehACV;
    }
    
    
    /* Calculate value of "Item Commissionable hACV" field */
    private Decimal setItemCommissionablehACV(OpportunityLineItem oli, Decimal basis) {
        
        // Declare method variables
        Decimal itemCommissionablehACV;
        
        // Get basic commissionable hACV
        itemCommissionablehACV = setItemhACV(oli,basis);
        
        // Apply reseller uplift as appropriate
        if (itemCommissionablehACV != null && oli.Reseller_Uplift__c) {
            itemCommissionablehACV = itemCommissionablehACV * 1.2; // 20% uplift
        }
        
        return itemCommissionablehACV;
    }
    
    
    /* Calculate value of "Item hACV" field */
    private Decimal setItemhACV(OpportunityLineItem oli,Decimal basis) {
    
        // Declare method variables
        Date itemhACVDeadline;
        Decimal itemhACV;
        String productCode = pbeDetailsMap.get(oli.PricebookEntryId).ProductCode;
                
        // Perform processing
        if (oli.Term_Start_Date__c == null) {
            itemhACV = null;
        } else { // oli.Term_Start_Date__c != null
            itemhACVDeadline = HelperCollection.addYearsAccountingForLeapYear(oli.Term_Start_Date__c,1);
            if (oli.Term_Start_Date__c.month() == 2 && oli.Term_Start_Date__c.day() == 29 && itemhACVDeadline.day() == 28) {
                itemhACVDeadline = itemhACVDeadline.addDays(1);
            }
            itemhACV = (
                oli.Product_License_Type_Picklist__c == 'Perpetual'
                ? basis / Decimal.valueOf(3)
                : oli.Term_End_Date__c == null || oli.Product_License_Type_Picklist__c == 'Other'
                    ? null
                    : oli.Term_End_Date__c < itemhACVDeadline || oli.Product_License_Type_Picklist__c == 'Services'
                        ? basis
                        : Decimal.valueOf(oli.Term_Start_Date__c.daysBetween(itemhACVDeadline) - HelperCollection.getNumLeapDaysInDateRange(oli.Term_Start_Date__c,itemhACVDeadline))
                            / (oli.Term_Length__c - HelperCollection.getNumLeapDaysInDateRange(oli.Term_Start_Date__c,oli.Term_End_Date__c))
                            * basis
            );
            if (itemhACV != null) {
                itemhACV = itemhACV.setScale(2);
            }
        }
        return itemhACV;
    }


    /* Calculate value of "Item hMY Extension" field */
    private Decimal setItemhMYExtension(OpportunityLineItem oli, Decimal basis) {
    
        // Declare method variables
        Date itemhMYDeadline;
        Decimal itemMYExtension;
        
        // Perform processing
        if (basis == null || oli.Item_Hybrid_ACV__c == null || oli.Term_Start_Date__c == null) {
            itemMYExtension = null;
        } else { // oli.Term_Start_Date__c != null
            itemhMYDeadline = HelperCollection.addYearsAccountingForLeapYear(oli.Term_Start_Date__c,3);
            itemMYExtension = (
                oli.Term_End_Date__c == null ||
                    oli.Term_End_Date__c < itemhMYDeadline ||
                    oli.Product_License_Type_Picklist__c == 'Services'
                ? 0
                : (
                    Decimal.valueOf(itemhMYDeadline.daysBetween(oli.Term_End_Date__c) - HelperCollection.getNumLeapDaysInDateRange(itemhMYDeadline,oli.Term_End_Date__c) + 1) /
                    (oli.Term_Length__c - HelperCollection.getNumLeapDaysInDateRange(oli.Term_Start_Date__c,oli.Term_End_Date__c)) *
                    basis
                ).setScale(2)
            );
        }

        return itemMYExtension;
    }
    
    
    /* Calculate MRR value of a given basis field.  Used to set "Item MRR" (with total
     * price as the basis) and "Item Annualized hACV" (with "Item hACV" as the basis).
     */
    private Decimal setItemMRR(OpportunityLineItem oli) {
        
        // Declare method variables
        Decimal itemMRR;
        
        // Perform processing
        if (
            oli.Item_Type__c == 'New' ||
            !oli.Renewable__c ||
            oli.Term_Start_Date__c == null ||
            oli.Term_End_Date__c == null
        ) {
            itemMRR = null;
        } else {
            itemMRR = setMRRValue(oli,HelperCollection.getLineItemPrice(oli)).setScale(2);
        }
        
        return itemMRR;
    }


    /* Calculate MRR value of a given basis for a given oli */
    private Decimal setMRRValue(OpportunityLineItem oli, Decimal basis) {
        
        // Declare method variables
        Date endDate = oli.Term_End_Date__c;
        Date startDate = oli.Term_Start_Date__c;
        Date startOfNextMonth;
        Decimal divisor = 0;
        Integer daysInMonth;
        
        // Calculate partial leading fragment of divisor
        if (startDate.day() != 1) {
            startOfNextMonth = startDate.addMonths(1).toStartOfMonth();
            daysInMonth = startDate.toStartOfMonth().daysBetween(startOfNextMonth);
            if (startDate.monthsBetween(endDate) == 0) {
                divisor += oli.Term_Length__c / daysInMonth;
            } else {
                divisor += Decimal.valueOf(startDate.daysBetween(startOfNextMonth)) / daysInMonth;
            }
            startDate = startOfNextMonth;
        }
        
        if (startDate <= endDate) {
        
            // Calculate partial trailing fragment of divisor
            startOfNextMonth = endDate.addMonths(1).toStartOfMonth();
            daysInMonth = endDate.toStartOfMonth().daysBetween(startOfNextMonth);
            if (endDate != startOfNextMonth.addDays(-1)) {
                divisor += Decimal.valueOf(endDate.toStartOfMonth().daysBetween(endDate.addDays(1))) / daysInMonth;
                endDate = endDate.toStartOfMonth().addDays(-1);
            }
            
            // Calculate main divisor (number of whole months)
            if (startDate <= endDate) {
                divisor += startDate.monthsBetween(endDate.addDays(1));
            }
        }
        
        // Perform calculation
        return (basis / divisor);
    }


    /* Update parent Opportunity fields that roll up from line items */
    public void setParentOppRollupFields() {
    
        // Declare method variables
        Decimal annualizedRenewalhACV;
        Decimal arr;
        Decimal baselineARR;
        Decimal baselineMRR;
        Decimal blra;
        Decimal commissionablehACV;
        Decimal commissionablehMy;
        Decimal commissionablehMYe;
        Decimal creditApplied;
        Decimal creditTotal;
        Decimal hAcv;
        Decimal hMyExtension;
        Decimal mrr;
        Decimal partnerReferralFee;
        Decimal totalPrice;
        String finalProductCodes;
        PricebookEntry pbe;
        
        for (Opportunity o : oppDetailsMap.values()) {
            
            // Reset opp-level variables
            annualizedRenewalhACV = 0;
            arr = 0;
            baselineARR = 0;
            baselineMRR = 0;
            blra = 0;
            commissionablehACV = 0;
            commissionablehMY = 0;
            commissionablehMYe = 0;
            creditApplied = 0;
            creditTotal = 0;
            finalProductCodes = '';
            hAcv = 0;
            hMyExtension = 0;
            mrr = 0;
            partnerReferralFee = 0;
            
            // Populate record-level variables
            for (OpportunityLineItem oli : oppLineItemsMap.get(o.Id)) {
            
                if (!(Trigger.isDelete && oliTriggerIdSet.contains(oli.Id))) {
                
                    // Reset line-item-level variables
                    pbe = pbeDetailsMap.get(oli.PricebookEntryId);
                    totalPrice = HelperCollection.getLineItemPrice(oli);
                
                    // Calculate rollup field values
                    if (oli.Item_Annualized_hACV__c != null && oli.Item_Type__c == 'Renewal') {
                        annualizedRenewalhACV += oli.Item_Annualized_hACV__c;
                    }
                    if (oli.Item_ARR__c != null) {
                        arr += oli.Item_ARR__c;
                    }
                    if (oli.Item_Baseline_ARR__c != null) {
                        baselineARR += oli.Item_Baseline_ARR__c;
                    }
                    if (oli.Item_Baseline_MRR__c != null) {
                        baselineMRR += oli.Item_Baseline_MRR__c;
                    }
                    if (oli.Item_BLRA__c != null) {
                        blra += oli.Item_BLRA__c;
                    }
                    if (oli.Item_Commissionable_hACV__c != null) {
                        commissionablehACV += oli.Item_Commissionable_hACV__c;
                    }
                    if (oli.Item_Commissionable_hMY__c != null) {
                        commissionablehMY += oli.Item_Commissionable_hMY__c;
                    }
                    if (oli.Item_Commissionable_hMY_Extension__c != null) {
                        commissionablehMYe += oli.Item_Commissionable_hMY_Extension__c;
                    }
                    if (oli.Item_Customer_Credit__c != null) {
                        creditApplied += oli.Item_Customer_Credit__c;
                    }
                    if (CREDIT_PRODUCT_CODES.contains(pbe.ProductCode)) {
                        creditTotal += totalPrice;
                    }
                    finalProductCodes += pbe.ProductCode + ' (' + oli.Quantity.intValue() + '); ';
                    if (oli.Item_Hybrid_ACV__c != null) {
                        hAcv += oli.Item_Hybrid_ACV__c;
                    }
                    if (oli.Item_MY_Extension__c != null) {
                        hMyExtension += oli.Item_MY_Extension__c;
                    }
                    if (oli.Item_MRR__c != null) {
                        mrr += oli.Item_MRR__c;
                    }
                    if (pbe.ProductCode == 'REF') {
                        partnerReferralFee += totalPrice;
                    }
                }
            }
            
            // Set Opp field values
            o.ACV__c = hAcv;
            o.Annualized_Renewal_hACV__c = annualizedRenewalhACV;
            o.ARR__c = arr;
            o.Baseline_ARR__c = baselineARR;
            o.Baseline_MRR__c = baselineMRR;
            o.Baseline_Renewal_Amount__c = blra;
            o.Commissionable_hACV__c = commissionablehACV;
            o.Commissionable_hMY__c = commissionablehMY;
            o.Commissionable_hMY_Extension__c = commissionablehMYe;
            o.Customer_Credit_Applied__c = creditApplied;
            o.Customer_Credit_Total__c = creditTotal;
            o.Final_Product_Codes__c = 
                ( o.Type == 'Renewal' && o.IsClosed && o.Baseline_Product_Codes__c != null )
                ? finalProductCodes
                : null;
            o.MRR__c = mrr;
            o.MY_Extension__c = hMyExtension;
            o.Partner_Referral_Fee__c = partnerReferralFee;
        }
        
        update oppDetailsMap.values();
    }


    /* Update "Renewed From Line Item Product Code" field */
    public static void setRenewedFromProductCode(List<OpportunityLineItem> oliList) {
    
        // Declare method variables
        Map<Id,OpportunityLineItem> oliDetailsMap = new Map<Id,OpportunityLineItem>();
        
        // Aggregate Renewed From line item Ids
        for (OpportunityLineItem oli : oliList) {
            if (oli.Renewed_From_Line_Item_Record_Id__c != null) {
                oliDetailsMap.put(oli.Renewed_From_Line_Item_Record_Id__c,null);
            }
        }    
        
        // Retrieve details of Renewed From line items
        oliDetailsMap = new Map<Id,OpportunityLineItem>([
            SELECT Id, PricebookEntry.ProductCode FROM OpportunityLineItem WHERE Id IN :oliDetailsMap.keySet()
        ]);
        
        // Set Renewed From Line Item Product Code
        for (OpportunityLineItem oli : oliList) {
            oli.Renewed_From_Line_Item_Product_Code__c =
                oli.Renewed_From_Line_Item_Record_Id__c == null
                ? null
                : oliDetailsMap.get(oli.Renewed_From_Line_Item_Record_Id__c).PricebookEntry.ProductCode;
        }
    }


    /* Update Contract "Software & Kits Purchased" field */
    public static void setSKPFieldOnContract(Set<Id> contractIdSet) {
    
        // Confirm method parameter not null or empty
        if (contractIdSet == null || contractIdSet.isEmpty()) {
            throw new HelperCollection.customException('setSKPFieldOnContract method parameter must not be null or empty.');
        }
                
        // Declare method variables
        String softwareString;
        List<Contract> contractList;
        
        // Retrieve data
        if (contractIdSet != null) {
            contractList = new List<Contract>([
                SELECT Id, (SELECT Id, PricebookEntry.Name, Quantity FROM Opportunity_Product_Contract__r ORDER BY PricebookEntry.Name)
                FROM Contract
                WHERE Id IN :contractIdSet
            ]);
        }
        
        // Perform processing
        if (!contractList.isEmpty()) {
            for (Contract c : contractList) {
                softwareString = '';
                for (OpportunityLineItem oli : c.Opportunity_Product_Contract__r) {
                    if (oli.PricebookEntry.Name != null) {
                        softwareString += oli.PricebookEntry.Name + ' (' + oli.Quantity.intValue() + ');';
                    }
                }
                c.Software_Kits_Purchased__c = softwareString;
            }
            update contractList;
        }
    }
}

 
AshlekhAshlekh
Hi,

If you are getting SOQL limit error it means there is SOQL which is calling numerious time. You need to check your and SOQL and DML should not be in for loop.
RossGRossG
Thanks.  Yeah I know thank you I just cannot locate where this is happening in the code above anywhere.  I see no soql queries in any for loops
RamuRamu (Salesforce Developers) 
Quite a small code to review :P Can you please provide debug log by reproducing this error so that I can see if I can get any clue out of it.