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
Vishal SawVishal Saw 

OpportunityLineItem On Opportunity

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

How to create this Opportunity line item?
Arun Kumar 1141Arun Kumar 1141
You can follow the below Code.

Trigger OpportunityTrigger on Opportunity(after Insert){
    if(trigger.isAfter){
        if(trigger.isInsert){
            InsertOpportunityLineItem.updateOpportunityWithLineItem(trigger.new);
        }
    }
}

public Class InsertOpportunityLineItem{
    public static void updateOpportunityWithLineItem(List<Opportunity> oppList){
        Product2 prod = [SELECT Id, Name FROM Product2 LIMIT 1];
        PriceBookEntry pbe = [SELECT Id FROM PriceBookEntry LIMIT 1];
        List<OpportunityLineItem> oppItemList = new <OpportunityLineItem>();
        for(Opportunity opp : oppList){
            OpportunityLineItem oppItem = new OpportunityLineItem();
            oppItem.OpportunityId = opp.Id;
            oppItem.PricebookEntryId = pbe.Id;
            oppItem.UnitPrice = 10;
            oppItem.Product2Id = prod.Id;
            oppItem.Quantity = 1;
            oppItemList.add(oppItem);
        }
        insert oppItemList;
    }
}
Prateek Prasoon 25Prateek Prasoon 25
trigger CreateOpportunityLineItem on Opportunity (after insert) {
    List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
    
    // loop through all of the new Opportunities
    for (Opportunity opp : Trigger.new) {
        // create a new Opportunity Line Item record
        OpportunityLineItem oli = new OpportunityLineItem();
        oli.OpportunityId = opp.Id;
        
        // set the default Product associated with the Opportunity
        // you may need to customize this line to fit your specific use case
        oli.PricebookEntryId = [SELECT Id FROM PricebookEntry WHERE Product2Id IN (SELECT Product2Id FROM OpportunityLineItem WHERE OpportunityId = :opp.Id) LIMIT 1].Id;
        // add the new Opportunity Line Item to the list
        oliList.add(oli);
    }
    
    // insert the new Opportunity Line Items
    insert oliList;
}

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