CRAFT CMS: Create a product type programmatically from a module

26 views Asked by At
  1. I need to create a product type from my module
  2. Ccreate my product after that with the product type created before.
  3. Create the default variant

how can I achieve that?

for example:

  // First, let's create a product type
            $productType = new ProductType();
            $productType->name = 'Payments';
            $productType->handle = 'payments';
            $productType->hasVariants = false;
            $productType->hasDimensions = false;
            $productType->setSiteSettings([$productTypeSite]);

            // Save the product type
            $test = Plugin::getInstance()->getProductTypes()->saveProductType($productType);
            dd($test);
            // Save the product type
//            \Craft::$app->getElements()->saveElement($productType);

            // Now, let's create a product
            $product = new Product();
            $product->typeId = $productType->id;
            $product->title = 'Windcave Payments - Save Cards';
            $product->slug = ElementHelper::generateSlug($product->title);
            $product->enabled = true;

            // Save the product
            \Craft::$app->getElements()->saveElement($product);

            // Now, let's create a variant for the product
            $variant = new Variant();
            $variant->productId = $product->id;
            $variant->sku = 'WINDCAVE-PAYMENTS'; // SKU for the variant
            $variant->price = 15.99;
            $variant->stock = 100;
            $variant->hasUnlimitedStock = true;
            $variant->isDefault = true; // This variant is the default one

            // Save the variant
            $saved = \Craft::$app->getElements()->saveElement($variant);
    ```

I get so many errors, like craft\services\Elements::saveElement(): Argument #1 ($element) must be of type craft\base\ElementInterface, craft\commerce\models\ProductTypeSite given, called in C:\laragon\www\windcavecraft\src\services\Windcave.php on line 35
0

There are 0 answers