I'm making a test class that creates 5 orders and upon insert, I get the error that you need to add products to orders.

I've got...

List<Product2> clothProds = [SELECT Id FROM Product2 WHERE Name='Clothing Voucher'];
    List<Product2> foodProd = [SELECT Id FROM Product2 WHERE Name='Food Pantry'];

to obtain the products I want for each order. Some will be food, others clothing.

I see an object "Order Product" in the org that isn't a Custom object, and has lookup fields for Order and for Product2, so I'm guessing this is what I need to make the association of Orders and their Products, but I can't for the life of me find the API Name or any info on how to make this in Apex.

All I'm really trying to do is insert Orders, and I have a way of getting the Products I need, and bridging these two things to insert them is where I'm having trouble. There are some triggers on Order insert, but they don't change the status or anything. Maybe there are complications there, but I don't think they're affecting this, so I'm hoping it's something standard that I'm just missing that somebody here can help me identify.


You'll want to see the OrderItem object documentation. Most importantly, you do not use "Product" to associate the product to the order; instead, you have to use the product's "price book entry" for the order's associated price book. That means that your code would start out like this:

Order orderRecord = new Order(Pricebook2Id=Test.getStandardPricebookId() ...);
insert orderRecord;
PricebookEntry[] clothProds = [select product2id from pricebookentry where product2.name = 'clothing voucher' and pricebook2id = :orderRecord.Pricebook2Id],
                  foodProds = [select product2id from pricebookentry where product2.name = 'food pantry' and pricebook2id = :orderRecord.Pricebook2Id];
 OrderItem[] orderLines = new OrderItem[0];
 ... make line items here ...

You may wish to create all of your products and price book entry values in the unit test directly to avoid data dependencies on production data as well; just insert the products, then the product's price book entries for the standard price book.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.