2

I've found out how to do this with other attributes.

For example a custom 'location' attribute:

    $product = $this->objectManager->get('Magento\Catalog\Model\Product')- >load($post['id']);
    $productResource = $this->objectManager->create('\Magento\Catalog\Model\ResourceModel\Product');
    $product->setLocation('test');
    $productResource->saveAttribute($product, 'location');

This saves the 'location' attribute value for my product.

But how would you do this for the stock attribute 'qty'?

3 Answers 3

0

This works for me:

public function __construct(
    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
)
{
    $this->stockRegistry = $stockRegistry;
    parent::__construct();
}

public function yourMethod() {
    $sku = 'XYZ';
    $qty = 70;
    $stockItem = $this->stockRegistry->getStockItemBySku($sku);
    $stockItem->setQty($qty);
    $stockItem->setIsInStock((bool)$qty); // this line
    $this->stockRegistry->updateStockItemBySku($sku, $stockItem);
}
0

public function __construct( \Magento\InventoryApi\Api\StockRepositoryInterface $productStockRepository ) { $this->productStockRepository = $productStockRepository; } $productStock = $productStockRegistry->getStockItem($entity->getId());

$productStock = $productStockRepository->get($entity->getId());

$productStock->setIsInStock(true);

$productStock->setQty(10);

$productStock->save();

0

Please follow the following code to save the stock value.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load();
$qty = 10;
$product->setStockData(
[
    'manage_stock' => '1',
    'is_in_stock' => '1',
    'qty' => $qty
]

);

Thanks.

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.