+ Start a Discussion
softwarensoftwaren 

inserting opportunity line item.PLEASE HELP!!!

Hi.İ have an object which name is order.This is like opportunity object and it must work syncronised with opportunity.İ fixed to add,delete and update order and same record which is on opportunity.İ want to do this operations on line items.When i add an order line item i must see this item under the opportunity record of same order.Please help me.This is so important for me.This is my codes but i got an error like " DUPLICATE_VALUE, This price definition already exists in this price book: []: Class.OrderItemToOppHandler.onBeforeInsert: line 11, column 1".Could you help me pls??

this is my class

public class OrderItemToOppHandler {

public void onBeforeInsert(List<Order_Products__c> OrdLineList){

List<OpportunityLineItem> OppItemToAdd = new List<OpportunityLineItem>();
List<PriceBookEntry> PRBList = new List<PriceBookEntry>();
PriceBook2 pr = [Select Id from PriceBook2 limit 1];
for (Order_Products__c ordp : OrdLineList) {
PRBList.add(new PriceBookEntry(pricebook2Id=pr.Id,product2Id=ordp.Product__c,unitprice=500));
}
insert PRBList;

for (Order_Products__c ordp : OrdLineList) {

OpportunityLineItem item = new OpportunityLineItem(Opportunityid = ordp.Order__c,PriceBookEntryId=PRBList[0].Id,Quantity=ordp.Quantity__c,ServiceDate=ordp.Date__c,UnitPrice=ordp.Sales_Price__c,TotalPrice=ordp.Total_Price__c );

OppItemToAdd.add(item);
}
insert OppItemToAdd;

}

}

 

Tim BarsottiTim Barsotti

Rather than inserting the pricebookentry, you should query the pricebook for the correct entry that already exists. Use that PricebookEntryID for your line item. 

softwarensoftwaren

Could you write it for me?im forcing to write this for 2 week.im a noob on apex.then i have to write delete and update these line items.thank you very much

Tim BarsottiTim Barsotti

This code is not that efficient in terms of algorithimic design. It also has one major assumption: you must have only have 1 active pricebook.

 

public void onBeforeInsert(List<Order_Products__c> OrdLineList){
	List<OpportunityLineItem> OppItemToAdd = new List<OpportunityLineItem>();
	Set<Id> ProductSet = New Set<Id>();
	ID pbId = null; 
	for (Order_Products__c ordp : OrdLineList) {
		ProductSet.add(ordp.Product__c);
		priceBookId = ordp.pbId;
	}
	List<PriceBookEntry> pbeList = [Select ID, Product2 where PriceBookId =: priceBookId];
	for (Order_Products__c ordp : OrdLineList) {
		Id PBEId = null;
		for(PriceBookEntry pbe: pbeList) {
			if(ordp.product2 = pbe.product2) {
				PBEId = pbe.Id;
			}
		}
		if(pbeId != null) {
			OpportunityLineItem item = new OpportunityLineItem(Opportunityid = ordp.Order__c, PriceBookEntryId=pbeId, Quantity=ordp.Quantity__c, ServiceDate=ordp.Date__c, UnitPrice=ordp.Sales_Price__c);
			OppItemToAdd.add(item);
		}
		
	}
	if(OppItemToAdd.size()>0){
		insert OppItemToAdd;
	}
}