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
Gaurav kumar 34Gaurav kumar 34 

pricebook entry is in a different pricebook than the one assigned to the opportunity): [PricebookEntryId]

Hello Guys,
Try to insert opportunityline item, getting error like 

"System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry is in a different pricebook than the one assigned to the opportunity): [PricebookEntryId]"


List<Opportunity> opp = [Select id From Opportunity o where id = 'XXXXXXXX'];
List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
    List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE Product2Id='XXXXX(productId)' AND PriceBook2.isStandard=true LIMIT 1];

    for (Opportunity oppty: opp) {
            OpportunityLineItem oli = new OpportunityLineItem(OpportunityId=oppty.Id,PricebookEntryId=priceBookList[0].Id,Quantity = 1,UnitPrice = 120);
                oliList.add(oli);
    }
     
    insert oliList;

Regards,
G
EnreecoEnreeco
Hi Gaurav,
you have to get the PRiceBookId from Opportunity and use it as a filter on the PriceBookEntry query: you MUST assign a PricebookEntry that is in the same PriceBook of the opportunity.

Hope this helps

--
May the Force.com be with you!