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
James SallyJames Sally 

Opportunity Line Item Trigger

Hi Folks,

I am looking for the functionality where I can have the trigger which will auto populate the Opp Line Item if I select the specific line item.

For example If I add the "ABC" Line item to the Opportunity, trigger will auto populate the another line Item "XYZ" to the same Opp.

I have one rough draft of the trigger which is not working:

trigger AutoCreateProduct on Opportunity (after insert) { 
    List<OpportunityLineItem> OpportunityLineItems = new List<OpportunityLineItem>(); 
    for (Opportunity newOpportunity: Trigger.New) { 
        if(newOpportunityLineItem == 'ABC'){
            OpportunityLineItems.add(new OpportunityLineItem(OpportunityId = newOpportunity.Id,PricebookEntryId ='01un00000000000',Quantity = 1,UnitPrice = 0)); (This should be the another Line Item "XYZ")

Experts please help me.

Thanks,
James
            
  
Lokesh KumarLokesh Kumar
HI James,

You can use the below Code Snippet and edit accordingly.
 
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;
}
Happy to help You!

Thanks,
Lokesh
My Blog: http://sf2learn.blogspot.in  (#
 
James SallyJames Sally
Hi Lokesh,

Thank you for the Reply!

Could you please elaborate the code. Where I need to put the "ABC" product detail and where to put the "XYZ" product detail?
 
Dhilip DussaDhilip Dussa
Here i'm getting error  List index out of bounds: 0:  can u please help me