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 }}

2 Answers 2

3

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);
1
  • hey thank you. this helped me a lot and was working great until a recent update. any idea what has changed? i think my product is no longer validating for some (new) reason.
    – Steve Mock
    Commented Mar 31, 2022 at 19:53
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.

1
  • 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
    Commented Oct 29, 2018 at 8:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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