Question

On a category page, I try to display the available quantity per product but I cannot succeed. On the admin interface, as described in the manual, I have enabled for the attribute called quantity_and_stock_status the Storefront Property -> Used in Product Listing.

On the code part, I override the list.phtml file on my custom theme(luma child), on path app\design\frontend\Vendor_name\Theme_name\Magento_Catalog\templates\product. I know it is a valid file as other modifications work. In there I call $_product_stock = $_product->getQty() but I get just 0. I also tried $_product->getExtensionAttributes()->getStockItem()->getQty() with no luck either.

Should I make a module for that or there is a configuration I am missing?

Thank you very much in advance for your help!

Was it helpful?

Solution

Please check this code will help you.

Create block file in the custom extension.

app/code/[VENDOR]/[EXTENSION]/Block/Product.php

and add below code in file.

<?php
namespace [VENDOR]\[EXTENSION]\Block;

class Product extends \Magento\Framework\View\Element\Template
{
    protected $_scopeConfig;
    protected $_stockInterface;
    protected $_productRepository;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\CatalogInventory\Api\StockStateInterface $stockInterface,
        \Magento\Catalog\Model\ProductRepository $productRepository
    ){
        $this->_scopeConfig = $scopeConfig;
        $this->_stockInterface = $stockInterface;
        $this->_productRepository = $productRepository;
        parent::__construct($context);
    }

    public function getStockMessage($productId){
        $_product = $this->getProductById($productId);
        $_stock = $this->getStock($_product);
        if($_stock <= $this->getThresoldQty()){
            return __('Only %1 left', $_stock);
        }
        return '';
    }

    public function getProductById($id)
    {
        return $this->_productRepository->getById($id);
    }

    public function getStock($_product)
    {
        return $this->_stockInterface->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId());
    }

    public function getThresoldQty(){
        return $this->_scopeConfig->getValue('cataloginventory/options/stock_threshold_qty', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
    }
}

Now add below code in list.phtml

$blockObj = $block->getLayout()->createBlock('[VENDOR]\[EXTENSION]\Block\Product');

Then you can call in the block inside your foreach loop.

<?php echo $blockObj->getStockMessage($_product->getId()); ?>

Hope this will help you.

Happy Coding.

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