1

The docs for v1 mention a method craft()->commerce_purchasables->saveElement().

This is omitted in the docs for v2. Does anyone know how I can create a product programmatically in PHP?

    $product = new Product();
        $product->title = "Test Product 1";
        $product->typeId = 2;
        $product->enabled = true;
        $product->promotable = true;

    $variant = new Variant();
            $variant->isDefault = true;

    $product->setVariants([$variant]);

    Craft::$app->getElements()->saveElement($product);

With the above code I get the following error:

Call to a member function getProductTypes() on null

I know the typeId is correct, because I can output it on a product template with {{ product.typeId }}

1
  1. Populate a product model ($product)
  2. Populate an array of variant models ($variants)
  3. $product->setVariants($variants);
  4. Craft::$app->getElements()->saveElement($product);

If step 4 returns false, validation errors occurred on the variants or product, and the errors be on the $product.

  • Thanks for your help. I'm getting the error Call to a member function getProductTypes() on null when I try to run my code. I've updated my question to add the code I'm trying. – themartin Oct 29 '18 at 8:00
1

You probably have it figured by now, but for anyone wondering, here's a complete working example.

use craft\commerce\elements\Product;
use craft\commerce\elements\Variant;

// Create product
$product = new Product();
$product->title = 'Hello world';
$product->typeId = 2;
$product->enabled = true;

// Create variant
$variant = new Variant();
$variant->title = 'hey';
$variant->sku = 'hey';
$variant->price = 123;
$variant->stock = 5;

// Save product with variant
$product->setVariants([$variant]);
Craft::$app->elements->saveElement($product);

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.