Question

I can't find a way to get the available quantity in Magento 2. I am Building a file to export products to CSV. Quantity must be stored in 'quantity_and_stock_status' but how to extract it I don't know.

Tried $product->getQty(); below is the part that builds CSV

foreach ($_columns as $_column) {
                switch ($_column) {
                    case 'link':
            $data[] = $product->getProductUrl();
                        break;
                    case 'id':
            $data[] = $product->getSku();
                        break;
                    case 'image_link':
            $data[] = $this->getMediaUrl() . 'catalog/product' . $product->getImage();
                        break;
                    case 'brand':
            $data[] = $product->getBrand();
            break;
                    case 'availability':
            $data[] = $product->getAttributeText('quantity_and_stock_status');
            break;
                    case 'inventory':
            $data[] = $product->getQty();
            break;
Was it helpful?

Solution

Try this

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

then call below method in your switch case by passing product id :

$_productStockQty = $this->_stockItemRepository->get($product->getId())->getQty();

or try this

$_productStock = $this->_stockItemRepository->get('product id'); 
$_productStockQty =  $_productStock->getQty(); 

or you can directly call this below function

$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockData = $stockItem->getQty();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top