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
shweta kumari 25shweta kumari 25 

How to add multiple opportunity line items when new opportunity record is created..

My requirement is to add about 10 opportunity line items when a new opporutntity gets created.

as of now I just have a trigger code which inserts one opportunity line item. If required I will share the code.

How to achieve this? Can I use a dataloader.

Please eloborate as required.

thanks
shweta

 
Raj VakatiRaj Vakati
You can able to do it by using trigger . To do it with data loader its manual work ..

Try this code with the trigger 

 
trigger UpdateOpportunityProductGroupsTrig on Opportunity (after insert) {
List<OpportunityLineItem> oppL = new LIst<OpportunityLineItem>() ;
for( Opportunity o : Trigger.new){

For ( integer i = 0 ; i<10 :i ++){

OpportunityLineItem item = new OpportunityLineItem(
		pricebookentryid='PRICE BOOK ID',
		TotalPrice=2000,
		Quantity = 2,
		OpportunityID = o.Id
	);
	oppL.add(item);
	
}
}

insert oppL ;

}

 
shweta kumari 25shweta kumari 25
Hi raj
Thanks reply. Its like hardcoding. any better way of doing this?

say in dev console, I will fetch the records created today and then I will loop through opporutnity line item and add.
Let me know.




 
Raj VakatiRaj Vakati
Dev console also you can able to do it.. 
List<Opportunity> opps = [Select Id from Opportunity where CreatedDate=TODAY];
for( Opportunity o : opps){

For ( integer i = 0 ; i<10 :i ++){

OpportunityLineItem item = new OpportunityLineItem(
		pricebookentryid='PRICE BOOK ID',
		TotalPrice=2000,
		Quantity = 2,
		OpportunityID = o.Id
	);
	oppL.add(item);
	
}
}

insert oppL ;

 
Ajay K DubediAjay K Dubedi
Hi shweta,

To create opportunity line item first we need to create price book, product, and PriceBookEntry.
More Info please check once below link ; 
https://www.youtube.com/watch?v=kuYatMj-_4U



Trigger Code:-

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()
            oli.OpportunityId=oppty.Id; 
            oli.PricebookEntryId=priceBookList[0].Id ;
            oliList.add(oli);
        }
    }

    insert oliList;
}

Hope this helps.

Thank You
Ajay Dubedi