+ Start a Discussion

field integrity exception: PricebookEntryId, unknown (versions 3.0 ...)

Hi All,


I am trying to add a product to opportunity through trigger whenever opportunity is created/updated.

Addition of Product is determined by A pickilst field on Opportunity. Which Means if the picklist field on opportunity has the value as ABC then it will search a Dummy product from a dummy Pricebook and add that.

But I m getting the error mentioned in Subject Line.


Below is the method used in trigger to add opportunity line item.


public static void insertProducttoOpp(Opportunity[] Opp) {

List<id> productList=new List<id>();
Map<string,ID> prodNamewithID = new Map<String, ID>();
Id priceBookId=[select id from Pricebook2 where Name='Sales Pricebook' limit 1].Id;

List<PricebookEntry> productIdList=[Select p.Product2Id From PricebookEntry p where p.Pricebook2Id=:priceBookId];

for(PricebookEntry P:productIdList){

// Name of the product is ABC Family. I am spliting string to get ABC.
for(Product2 p:[select Id,Name from Product2 where id IN: productList]){
List<String> productName=p.Name.split(' ');

List<ID> oppProdId =prodNamewithID.values();
List<Opportunity> oppList = new List<Opportunity>();//List to Update opportunity without product
List<OpportunityLineItem> oliList = new List<OpportunityLineItem>(); //to create Product
Map<ID, ID> pbeMap = new Map<ID, ID>();// Pricebook entry with product ID
for (Opportunity o :Opp){
// Build the map to use to match Products to PriceBookEntries
for(PriceBookEntry pbe : [select Id, Product2Id from PriceBookEntry where PriceBook2Id =: priceBookId and Product2Id in :oppProdId]) {
pbeMap.put(pbe.Product2Id, pbe.id);
//Build the OpportunityLineItems for each Opportunity
for(Opportunity op : oppList) {
OpportunityLineItem oli = new OpportunityLineItem(OpportunityId = op.id, PriceBookEntryId = pbeMap.get( prodNamewithID.get(op.Product_Family__c)), Quantity = 1, UnitPrice = op.Total_amount__c);

if(!oliList.isEmpty()) {
//Create the OpportunityLineItems
insert oliList;