1

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;

1 Answer 1

0

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();
1
  • No luck. Gives error "...call to a member function get() on null in.... " Any idea what this is? Thanks! Commented Jan 14, 2020 at 8:58

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.