+ Start a Discussion
rdgrdg 

APEX code to insert opportunity line item.

Hi guys,

 

Still a noob with APEX so any help will be very appreciated.

 

My requirement is that I need to insert an OLI to a new Opportunity created with a certain criteria (depending on record type).

 

The pricebook/product will always be the same.

 

Thanking you guys in advance!

 

 

regards,

 

DG

Best Answer chosen by Admin (Salesforce Developers) 
AdrianCCAdrianCC

Hello rdg,

 

What you need is an apex trigger. See here: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers.htm

 

trigger CreateOLI on Opportunity (after insert) {
	List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();

	List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE Product2Id='certain_id' AND PriceBook2.isStandard=true LIMIT 1];

	for (Opportunity oppty: Trigger.new) {
		if (/*certain_criteria*/) {
			//create new Oli
			OpportunityLineItem oli = new OpportunityLineItem(OpportunityId=oppty.Id, PricebookEntryId=priceBookList[0].Id /*rest of required fields*/);
			oliList.add(oli);
		}
	}

	insert oliList;
}

 

You'll need to fill in the comments with your specific code.

 

Thanks,

Adrian

All Answers

AdrianCCAdrianCC

Hello rdg,

 

What you need is an apex trigger. See here: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers.htm

 

trigger CreateOLI on Opportunity (after insert) {
	List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();

	List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE Product2Id='certain_id' AND PriceBook2.isStandard=true LIMIT 1];

	for (Opportunity oppty: Trigger.new) {
		if (/*certain_criteria*/) {
			//create new Oli
			OpportunityLineItem oli = new OpportunityLineItem(OpportunityId=oppty.Id, PricebookEntryId=priceBookList[0].Id /*rest of required fields*/);
			oliList.add(oli);
		}
	}

	insert oliList;
}

 

You'll need to fill in the comments with your specific code.

 

Thanks,

Adrian

This was selected as the best answer
rdgrdg

Thank you thank you thank you!

 

Works great!

EllenHEllenH

Hi rdg,

 

I was looking to do the same thing, based on an indicator on the opp, however, when I subsituted in the required fields for the product insertion, I get an error.

 

I am trying to insert the name of the product, quantity and total proce, however, it complains about the name.  Said it is an invalid field for SObject OpportunityLineItem

 

Wondering how you insert the name.

 

I tried using a variety of combinations with product2.name, pricebookentry.product2.name, etc...

 

How did you resolve this?

 

Thanks very much.

EllenHEllenH

Most helpful!

Thanks AdrianCC