+ Start a Discussion
sfdeveloper12sfdeveloper12 

Create Opportunity Line Item Record when new opportunity is created

Hello,
I want to create automatic opportuinty line item when opportunity is created. How is this possible. I want to create of particular Product name suppose "Accomodation". I have written a code. 
trigger insertOppLineItem on Opportunity (after insert, after update) {
 system.debug('****************InTrigger**********************');
    
    if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate)){
        String OpportunityID ;
        
    for(Opportunity o : Trigger.new){ 
        system.debug('OpportunityID 8 -->'+o.Id);
        OpportunityID = o.Id;
    
        if(OpportunityID  != null) 
        {
            List<Opportunity> opp = [select Id , No_of_Nights__c from Opportunity where ID =:  OpportunityID  ]; 
               system.debug('Opportunity 14.......... -->'+opp );

          //  List<OpportunityLineItem> vList = new List<OpportunityLineItem >();
           for(OpportunityLineItem v : trigger.new){
            o.No_of_Nights__c = v.Quantity;
        
                //vList.add(v);          
             }
               

        } 
        upsert v; 
    }   
}
}


How is this achivable?


Thanks &Regards,
Utkarsha
Best Answer chosen by sfdeveloper12
v varaprasadv varaprasad
Hi Patil,

To create opportunity line item first we need to crate pricbook,product and PriceBookEntry.
More Info please check oncebelow link ; 
https://www.youtube.com/watch?v=kuYatMj-_4U
 
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.

Thanks
Varaprasad​

 

All Answers

v varaprasadv varaprasad
Hi Patil,

To create opportunity line item first we need to crate pricbook,product and PriceBookEntry.
More Info please check oncebelow link ; 
https://www.youtube.com/watch?v=kuYatMj-_4U
 
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.

Thanks
Varaprasad​

 
This was selected as the best answer
Ajay K DubediAjay K Dubedi
Hi
Utkarsha,
Try the Code below.
Trigger Code:-
trigger Create_Opportunity_Line_Item_When_Create_Opportunity on Opportunity (after insert) 
{
    Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where          IsStandard = true limit 1];
    
    Product2 prd1 = new Product2 (); // ----> Create  product
    prd1.Name='Accomodation';
    insert prd1;
    
    PricebookEntry pbe1 = new PricebookEntry ();  //------->Create PriceBookEntry
    pbe1.Product2ID=prd1.id;
    pbe1.Pricebook2ID=standardPb.id;
    pbe1.UnitPrice=50;
    pbe1.isActive=true;
    insert pbe1;
    
    List<OpportunityLineItem>  oplist=new List<OpportunityLineItem>(); //-->Create List to store OpportunityLineItem
    
    for(Opportunity opp: Trigger.New)
    {
        OpportunityLineItem oppli = new OpportunityLineItem(); //---->Create OpportunityLineItem.
        oppli.PricebookEntryId=pbe1.Id;
        oppli.OpportunityId = opp.Id;
        oppli.Quantity = 5;
        oppli.TotalPrice = 10.0;
       oplist.add(oppli);
    } 
    insert oplist; //----->insert OpportunityLineItem
 }

Regards,
Ajay
If this answers your query please mark this question as a solved so that it can be filtered out from  unsolved questions.

 
sfdeveloper12sfdeveloper12
/* This trigger will insert opp ine item on creation of new opp */
trigger InsertOppLineItemOnOpp on Opportunity (after insert) {
    
    Set<id> oId = new set<id>();
    for(Opportunity opp : trigger.new){
        oId.add(opp.Id);
    }
    
    Opportunity opp = [select Id , No_of_Nights__c,CurrencyIsoCode,RecordTypeId,recordtype.name,Arrival_Date__c,Guest_Name__c, 
                       Departure_Date__c from Opportunity where ID =: oId];
    system.debug('opp************'+opp);
     
    PriceBookEntry p = [SELECT Id, Product2Id, Product2.Id, Product2.Name, CurrencyIsoCode FROM PriceBookEntry WHERE 
                        Product2Id='01t5E000000btVk' and CurrencyIsoCode =: opp.CurrencyIsoCode and Pricebook2Id = '01s5E0000004rHG'];
    system.debug('p***************'+p);
    
    string recordtypename = Schema.SObjectType.Opportunity.getRecordTypeInfosById().get(opp.recordtypeid).getname();
    system.debug(' recordtypename*************'+recordtypename);
    
    List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
    for(Opportunity op : trigger.new){
        if(opp.No_of_Nights__c!= null && opp.RecordType.Name == recordtypename){
             OpportunityLineItem oli = new OpportunityLineItem();
             oli.OpportunityId = opp.Id;
             oli.Quantity = opp.No_of_Nights__c;
             oli.PricebookEntryId = p.Id;
             oli.Guest__c = opp.Guest_Name__c;
             oli.Departure_Date__c = opp.Departure_Date__c;
             oli.UnitPrice = 0;
             oliList.add(oli);
            system.debug('oliList------------'+oliList);
        }   
     }
     insert oliList;
   
    }
}

This is working now. Both answers posted by you are correct.
Mohammad Rafi 5Mohammad Rafi 5
thank you ajay sir
 
Dhilip DussaDhilip Dussa
Here I'm getting error System.ListException: List index out of bounds: 0: 

i think this line only oli.PricebookEntryId=priceBookList[0].Id ;

please help me