I'm trying to create custom products with Commerce 2. More specifically I'm trying to have custom ui for customers to build their purchasable products.
I thought that I would be able to create single Product and it's variation and then make some adjustments for price and some other fields. It seems that I'm able to programmatically create custom OrderItem, set all custom fields as needed and then add item to cart. Apparently this works as expected.
But I'm having issues getting custom price set for the OrderItem. Seems that I have to create separate ProductVariation for each ordered item, even if it's the same in all practical purposes. Only differing data is price. I tried using instructions here(http://docs.drupalcommerce.org/v2/recipes/orders.html).
$order_item = \Drupal\commerce_order\Entity\OrderItem::create([ 'type' => 'custom_order_item_type', 'purchased_entity' => $variation_red_medium, 'quantity' => 2, 'unit_price' => $variation_red_medium->getPrice(), ]); $order_item->save();
If I leave unit_price empty, to be set later, I get TypeError: Argument 1 passed to Drupal\commerce_order\Entity\OrderItem::setUnitPrice() must be an instance of Drupal\commerce_price\Price, null given, called in /var/www/drupalvm/web/modules/contrib/commerce/modules/order/src/OrderRefresh.php on line 143
I'm trying to do this:
// You can also set the price with setUnitPrice. $unit_price = new \Drupal\commerce_price\Price('9.99', 'USD'); $order_item->setUnitPrice($unit_price); $order_item->save();
Only way I got this to work was setting ProductVariation price separately, but this then updates the basic price on the Product page, which really isn't what I'm looking for..
On the documentation it says this:
* adjustments [OPTIONAL] - [Array(Drupal\commerce_order\Adjustment)] * Array of any price adjustments.
but I can't get this far because OrderItem creation fails because of the missing price. If I set price, it just get's overridden from the initial ProductVariation.
I suppose that I can get around this by creating those ProductVariations on the fly, but I'd rather not since I don't need those for anything else than this single purchase.
So I guess I'm looking for some instructions on how to do dynamic products. Tried PurchasableEntity initially, but couldn't get that working at all and wasn't able to reverse engineer my needs from ProductBundle or similar.
Or any info how to set OrderItem price independently from ProductVariation.