I have following code to automatically create products in magento 2.4.5-p1.
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace VendorModuleModel;
use MagentoCatalogModelProduct;
use MagentoCatalogModelProductRepository;
use MagentoCatalogInventoryModelStockItem;
class SaveProduct
{
/**
* @var Product
*/
private $product;
/**
* @var ProductRepository
*/
private $productRepository;
/**
* @var Item
*/
private $stockItem;
/**
* SaveProduct constructor.
*
* @param MagentoCatalogModelProduct $product
* @param MagentoCatalogModelProductRepository $productRepository
* @param MagentoCatalogInventoryModelStockItem $stockItem
*/
public function __construct(
Product $product,
ProductRepository $productRepository,
Item $stockItem
) {
$this->product = $product;
$this->productRepository = $productRepository;
$this->stockItem = $stockItem;
}
/**
* @throws MagentoFrameworkExceptionCouldNotSaveException
* @throws MagentoFrameworkExceptionInputException
* @throws MagentoFrameworkExceptionStateException
*/
public function execute(array $productsToPatch, array $freeSkusArray,
$manufacturerId)
{
for($i=0; $i<1; $i++) {
//for($i=0; $i<count($productsToPatch)-1; $i++) {
$this->product->setAttributeSetId(4);
$this->product->setTypeId('simple');
$this->product->setSku($freeSkusArray[$i]);
$this->product->setName($productsToPatch[$i]['name']);
$this->product->setPrice(999);
$this->product->setStatus(1);
$this->product->setVisibility(0);
$this->product->setCustomAttributes(
array(
'manufacturer_sku' => $productsToPatch[$i]['sku'],
'manufacturer_ean' => $productsToPatch[$i]['ean'], // ignore if null
'manufacturer' => $manufacturerId,
'manufacturer_name' => $productsToPatch[$i]['name'],
'vpe' => $productsToPatch[$i]['vpe'],
'umkarton' => $productsToPatch[$i]['umkarton'],
'cost' => 999
)
);
/* $this->product->setStockData(
array(
'is_in_stock' => 1,
'qty' => 500
)
); */
$this->productRepository->save($this->product);
return $freeSkusArray[$i];
}
}
}
Like you can see I commented out “setStockData” thus its a deprecated function.
Now I wonder what is the correct way to set stock for new products?
MagentoCatalogModelProduct
offers setQty
function, but it has no effect when creating a new product
I also tried with MagentoCatalogInventoryModelStockItem
but didnt had success either
Any suggestions or pointing in right direction would be appreciated 🙂
P.S: I only create simple products
at the moment