I'm writing a trigger to create 13 opportunity line item in opportunity if the opportunity is 'New System'. I'm trying to create it using name of the product, it works but it takes only one name for the 13 products following is my trigger, In map i've taken he product name & quantity please help.....

trigger CreateOpportunityLineItems on Opportunity (after insert) 
    List<OpportunityLineItem> listOppLineItem = new List<OpportunityLineItem>();
    List<PriceBookEntry> priceBookList = new List<PriceBookEntry>();

    Map<string,Integer> productMap = new  Map<string,Integer>();
    productMap.put('Focus - Station - U',1);
    //productMap.put('Focus - EDC - M',1);
    productMap.put('Posi - XT3215 P',1);
    productMap.put('Drawer - MS 423',1);
    productMap.put('Print - Epson T20II',1);
    productMap.put('Print - Epson U220B E',1);
    productMap.put('Net - Netgear Router',1);
    productMap.put('Part - Cable & Connector Kit',5);
    productMap.put('ProSrv - ProServ Pkg',1);
    productMap.put('ProSrv - Prog - Standard',8);
    productMap.put('ProSrv - Install',1);
    productMap.put('ProSrv - Training - Mgr',6);
    productMap.put('ProSrv - Training - Emp',2);
    productMap.put('ProSrv - On-Site',10);


    //for(String s : productMap.keyset())
        //System.debug('----Pricebook Entry----'+s);
        //PriceBookEntry priceBook 
        priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name, UnitPrice
                                              FROM PriceBookEntry 
                                              WHERE Product2.Name =: productMap.keyset()];
        System.debug('----priceBookList ----'+priceBookList );

       // priceBookList.add(priceBook);



    for (Opportunity oppty : Trigger.new)        
        if(oppty.type == 'New System')
            for(PriceBookEntry pbe : priceBookList)
                OpportunityLineItem oli = new OpportunityLineItem(OpportunityId = oppty.Id, PricebookEntryId = priceBookList[0].Id, Name=pbe.Product2.Name, Quantity=productMap.get(pbe.Product2.Name), TotalPrice=(pbe.UnitPrice)*(productMap.get(pbe.Product2.Name)));

    if(listOppLineItem.size() > 0){
        insert listOppLineItem;

I see 2 candidates for improvement in your code, of which probably #2 is causing the issue:

  1. PricebookEntry query. I'd replace the WHERE Product2.Name =: productMap.keyset() by WHERE Product2.Name IN :productMap.keyset() Not 100% sure if this will cause a problem though.
  2. OpportunityLineItem creation. PricebookEntryId = priceBookList[0].Id will always assign the first product in the list to this opportunitylineitem. I expect you want to to PricebookEntryId = pbe.Id instead so the current pricebookentry is assigned to the oli.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.