Question

I have the following in our helper:

public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Catalog\Model\Product $product,
    \Magento\Catalog\Model\Product\Option $option,
    \Magento\Checkout\Model\Cart $cart,
    array $data = []
) {
    $this->_productCollection = $productCollection;
    $this->_productFactory = $productFactory;
    $this->_prod = $product;
    $this->_option = $option;
    $this->_cart = $cart;
    parent::__construct($context);
}

public function createProduct($sku, $name, $weight, $price, $jsonMix, $jsonPost, $type = 'simple')
{
    $mixProduct = $this->_productFactory->create();

    $mixProduct->setSku($sku); // Set your sku here
    $mixProduct->setName($name); // Name of Product
    $mixProduct->setWeight($weight); // weight of product
    $mixProduct->setPrice($price); // price of product
    $mixProduct->setDescription('' . $jsonMix . ' ' . $jsonPost);

    // defaults
    $mixProduct->setAttributeSetId(4); // Attribute set id
    $mixProduct->setStatus(1); // enabled/ disabled 1/0
    $mixProduct->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
    $mixProduct->setTaxClassId(1); // Tax class id
    $mixProduct->setTypeId($type); // type of product
    $mixProduct->setWebsiteIds(array(1));

    $mixProduct->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 0,
            'is_in_stock' => 1,
            'qty' => 1
        )
    );

    // now save the product
    try{
        $mixProduct->save();
    } catch(Exception $e){
        echo $e->getMessage();
    }

    var_dump($mixProduct->getId()); die();

}

Calling it from a controller works only the first time, successfully creating a product in the backend. But any subsequent tries seem to edit the already existing product instead of creating a new one.

Does anyone know why?

Was it helpful?

Solution

Injecting Magento\Catalog\Model\Product in the constructor means, you get the same instance every time (like a singleton).

That does not make sense for models. Instead you should inject Magento\Catalog\Model\ProductFactory and then instantiate the product like this:

$product = this->productFactory->create();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top