Question

Trying to get qty of the simple product for csv.

Using $data[] = $product->getQty(); but it returns 0. Looks like it returns default value. How to get the actual quantity of the products?

Was it helpful?

Solution

To get a simple product stock Quantity, Refer to the below code.

app/code/Vendor/Module/Block/StockData.php

<?php
namespace Vendor\Module\Block;
class StockData extends \Magento\Framework\View\Element\Template
{    
    protected $_stockItemRepository;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository,
        array $data = []
    )
    {
        $this->_stockItemRepository = $stockItemRepository;
        parent::__construct($context, $data);
    }

    public function getStockItem($productId)
    {
        return $this->_stockItemRepository->get($productId);
    }
}
?>

Now you can get quantity in your template file like this.

$productStockData = $block->getStockItem($product->getId());
echo $productStockData->getQty();

Or you can use objectManager (Not Preferable)

<?php
    $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
    $stockItemRepository = $objectManager->get('\Magento\CatalogInventory\Model\Stock\StockItemRepository');
    $productStockData = $stockItemRepository->get($product->getId());
    echo $productStockData->getQty();
?>

OTHER TIPS

This worked for me

echo $_product->getExtensionAttributes()->getStockItem()->getQty();

Magento 2: after get qty its show zero always

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top