+ Start a Discussion
ruchika Nayyarruchika Nayyar 

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

trigger opportunitytrigger1 on Opportunity (after insert) {
    list<opportunityLineItem> olilist= new list<OpportunityLineItem>();
    for(opportunity op:Trigger.New)
    {
        if(op.product!=null)
        {
            OpportunityLineItem oli= New OpportunityLineItem();
            oli.Product= op.Product;
            oli.Opportunity= op.ID;
            olilist.add(oli);
        }
    }
      if(olilist!=null&&olilist.size()>0)
          insert olilist;
}

error-invalid field for product sobject 
VineetKumarVineetKumar
You don't associate your product to your opportunity line item directly.
Instead you also need to associate to the correct pricebook, as that in your opportunity.
The code would look something like below.
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;
Let me know if this helps.
ruchika Nayyarruchika Nayyar
Where product2id= <requiredproductid> in this line error is coming expecting a colon ,found <.
Why we used required product
VineetKumarVineetKumar
You need to replace <requiredproductid> with the product Id that you want to associate to the OLI.