Code works fine on 2.0.4
Create a product
$product->load(1)/**
* @var \Magento\Catalog\Model\Product
*/
$product->load(1);
/**
* @var \Magento\CatalogInventory\Api\StockRegistryInterface
*/
$productStockData = $this->stockRegistry->getStockItem($product->getId());
$productStockData->setData('is_in_stock', 1);
$productStockData->setData('qty', 5);
$productStockData->setData('manage_stock', 1);
$productStockData->save();
$product->save();
The product should update its stock data and set to manage stock as true.
The product does not change stock data and does not throw an exception or warning.
I'm able to set the products weight and other attributes just fine with similar code, but cannot change its stock data after the product has been created.
I have the same problem.
I am using:
public function updateProductStock($productId) {
$product=$this->_product->load($productId);
$stockItem=$this->_stockRegistry->getStockItem($item['product_id']);
$stockItem->setData('is_in_stock',$stockData['is_in_stock']);
$stockItem->setData('qty',$stockData['qty']);
$stockItem->setData('manage_stock',$stockData['manage_stock']);
$stockItem->setData('use_config_notify_stock_qty',1);
$stockItem->save();
$product->save();
}
I was able to fix my issue like this:
$stockData = $this->getTotalStock($productId);//Load product stock.
$product=$this->_product->load($productId); //load product which you want to update stock
$product->setStockData(['qty' => $stockData, 'is_in_stock' => $stockData]);
$product->setQuantityAndStockStatus(['qty' => $stockData, 'is_in_stock' => $stockData]);
$product->save();
Can you show $this->getTotalStock($productId)?
It is a custom function on a custom module I created to load the stock of the product.
My module is to add stock as a Lot instead of manually. so admin adds a product lot ID with a lot stock and the function looks for all the lots that are attached to the product and returns the total stock of all lots for that product.
Basically $stockData is just a qty number.
I have the same issue when creating a product for the first time programatically. I create the product with its factory and set all the values. For stock I create a ProductExtension object with the stockItem information and set it. It does save all the data, but it does not manage the stock. I use the same values in a json and post it using the api and it works well the problem is programatically doing so.
Magento 2.0.10, PHP7
Hi @Jrb1x I was just wondering why you closed this as we were having the same issue and were following this issue. Was there a resolution this? Thanks.
@joesken I showed the solution to the issue above.
you can see my code how I was able to set product stock programatically getting a total stock product stock which is just a number ex. 5, then loading the product and setting the stock data and the quantity and stock status then saving the product.
Most helpful comment
I was able to fix my issue like this: