You need to sign in to do that
Don't have an account?
Bhavin 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;
}
}
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;
}
}
All Answers
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();
}
}
}
Why Select pricebook before insert??