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
niki s 7niki s 7 

Write a trigger on Opportunity for bulk update

Write a trigger on Opportunity, when an Opportunity will be insert an Opportunity Line Item should be insert by default with any of the Product associated with Opportunity.

It should be able to handle bulk records 
Suraj Tripathi 47Suraj Tripathi 47
Hi, niki,
Try this code -
trigger opportunitytrigger1 on Opportunity (after insert) {
 list<opportunityLineItem> olilist= new list<OpportunityLineItem>();
    List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE Product2Id = <RequiredProductId> AND PriceBook2.isStandard=true LIMIT 1];
    for(opportunity op:Trigger.New){
        OpportunityLineItem oli= New OpportunityLineItem();
        oli.OpportunityId = op.ID;
        oli.PricebookEntryId = priceBookList[0].Id;
        olilist.add(oli);
    }
    if(olilist!=null&&olilist.size()>0)
        insert olilist;
}
You need to replace <requiredproductid> with the product Id that you want to associate with the OLI.

If you found this helpful,
Please mark it as the best answer.

Thank you
niki s 7niki s 7
Thanks