I create a product entity instance like below. However, it results in : "Recoverable fatal error: Argument 1 passed to Drupal\commerce_order\OrderItemStorage::createFromPurchasableEntity()
must implement interface Drupal\commerce\PurchasableEntityInterface, null given". I'm missing how to implement PurchasableEntityInterface.

How to complete this correctly? Thanks.

use Drupal\commerce_product\Entity\Product;
use Drupal\commerce\PurchasableEntityInterface;

$my_product = Product::create([
  'type' => 'food',
  'langcode' => 'en',
  'created' => REQUEST_TIME,
  'changed' => REQUEST_TIME,
  'uid' => 1,
  'title' => 'My product',
  'body' => [
    'summary' => '',
    'value' => '<p>Lorem Ipsum</p>',
    'format' => 'full_html',
  ],
]);
$my_product->save();

Comments

jpdaut created an issue. See original summary.

bojanz’s picture

Title: creating a product instance in code » Error when creating a product
Category: Support request » Bug report

The support request is a duplicate of #2811529: How to create commerce products from code, someone will reply there.

Which other method were you calling when you got the error? Was it just this save?
You generally need a variation along with the product, but the system should not crash.
Reclassifying as a bug report.

jpdaut’s picture

bojanz the code above was all I was using. However I now think there's no bug : my create() call was missing the variations argument, which is required, as I figured out after reading mbreden's very helpful post that came in today.

If I do a complete example like he suggests, it works fine. So to me I think there's no bug here, this issue can be closed. Thank you.

mglaman’s picture

Status: Active » Closed (works as designed)

Per #3 this is a non-issue afterall.