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
SubhamSubham 

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){
productList.add(p.Product2Id);
}

// 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(' ');
prodNamewithID.put(productName[0],p.ID);
}

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
if(!Opp.isempty()){
for (Opportunity o :Opp){
oppProdId.add(prodNamewithID.get(o.Product_Family__c));
oppList.add(o);
}
}
// 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);
oliList.add(oli);
}

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

Regards,

S