+ Start a Discussion
Bhavin Mehta 20Bhavin Mehta 20 

Add Orderitem Records through trigger

I am trying to add one order product as default whenever a custom field in Order Object (Service_Type__c) is Postpaid. I am stuck at below step. Please help to complete the same as to how can I insert product name, code etc.



trigger createlineitems on Order (after insert) {
    list<Orderitem> lineitems = new list<Orderitem>();
    for (Order o : trigger.new){
        if(o.Service_Type__c == 'Postpaid')
        {
            Orderitem oitem = new Orderitem();
              oitem.OrderId = o.id;
           oitem.Quantity = 1;
            oitem.UnitPrice = 200;
  oitem.PricebookEntryId =?????
     
lineitems.add(oitem);
 
   }
        
     insert lineitems;   
    }
    
}
Best Answer chosen by Bhavin Mehta 20
pconpcon
You will need to figure out your what your PricebookEntry should be.  You can get this by querying your PricebookEntry object before your loop  and then assign that to your orderItem.

All Answers

pconpcon
You will need to figure out your what your PricebookEntry should be.  You can get this by querying your PricebookEntry object before your loop  and then assign that to your orderItem.
This was selected as the best answer
Bhavin Mehta 20Bhavin Mehta 20
Thanks!! Trigger is working as expected, also I needed to select the pricebook before insert.


trigger createlineitems on Order (before insert,after insert) {
      Pricebook2 standardBook = [SELECT Id FROM Pricebook2 WHERE IsStandard = true];
    if(trigger.isbefore)
    {
        for(Order saord : trigger.new)
        {
            saord.Pricebook2Id = standardbook.id;
            
        }
    }
    
    if(trigger.isafter)
    {
 
    list<Orderitem> lineitems = new list<Orderitem>();
        Pricebookentry entry = [SELECT Id,unitprice FROM PricebookEntry WHERE Pricebook2Id = :standardBook.Id AND Product2.ProductCode = 'ALW'];
    for (Order o : trigger.new){
        if(o.Service_Type__c == 'Prepaid')
        {
            
            
            Orderitem oitem = new Orderitem();
            oitem.OrderId = o.id;
           
          oitem.PricebookEntryId = entry.Id;
            oitem.UnitPrice = entry.UnitPrice;
            oitem.Quantity = 1;
           
        lineitems.add(oitem);
      
   }
        
        
    }
    try{
    insert lineitems;
    }
    catch (Exception e)
    {
        e.getMessage();
    }
    }
    
}
Pedro ReyesPedro Reyes
HI!!!!
Why Select pricebook before insert??