0

I want to throw an exception on insert(opportunity Line Item) if selected inventory is already selected in Opportunity or not. This code is working fine for one record when inventory is already selected then it gives an error but when I am trying to bulk insert Opportunity Line-item and if some inventories are not selected in other opportunities then also I am getting an error in all inventories i.e Inventory already selected even though some inventories are not selected. Below is my code which I am calling from after insert trigger.

public static void DuplicateInventorycheck(List<OpportunityLineItem> newItemValues,Map<Id,OpportunityLineItem> oldItemValues)
{
    List<Id> inventoryItemIds =new List<Id>();
    List<OpportunityLineItem> opportunityLineItems  =[SELECT InventoryItem__c FROM OpportunityLineItem WHERE Id=:newItemValues];
    for(OpportunityLineItem OLI:opportunityLineItems)
    {
        inventoryItemIds.add(OLI.InventoryItem__c);
    }

    Map<Id,Id> inventoryIds=new Map<Id,Id>();
    List<Opportunity> oppslist =        [SELECT InventoryItem__c
                                        FROM Opportunity
                                        WHERE InventoryItem__c IN : inventoryItemIds
                                        AND InventoryItem__c != NULL];
    for(integer i=0;i<oppslist.size();i++)
    {
        inventoryIds.put(oppslist[i].InventoryItem__c,oppslist[i].InventoryItem__c);
    }
    for(OpportunityLineItem OLI:opportunityLineItems)
    {
        for(Id Ids:inventoryIds.values())
        {
            if(OLI.InventoryItem__c == Ids)
            {
                throw new OLIInventoryItemException(Label.InventoryItemAlreadySelected);
            }
        }

    }

What amendement is required so that partial Opportunity Line Item records should get inserted without failure.

1
  • Are you looking for a hard stop error message to end users or is this bulk update taking place in a background operation?
    – TSmith
    Jun 17, 2020 at 11:21

1 Answer 1

1

You currently throw an Exception, which means the whole transaction will fail and thus all opportunitylineitems in the trigger will fail.

If you want to only make the specific opportunitylineitems fail that have a matching inventoryitem, do not throw an exception but use .addError() to add an error to individual records in the trigger.

        if(OLI.InventoryItem__c == Ids)
        {
            OLI.addError(Label.InventoryItemAlreadySelected);
        }
2
  • Clairboise It won't be possible to use add error in after triggerhttps://salesforce.stackexchange.com/questions/9121/using-adderror-method-in-after-insert-trigger
    – Avesh
    Jun 17, 2020 at 10:24
  • 2
    That's not correct. You can use addError perfectly fine in after inser trigger. Jun 17, 2020 at 10:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .