Magento 2 – How to Show Quantity Left on Listing Page

magento2productquantitystock

I need to show Qty left message with qty of product in product detail page with below condition.
If the available stock is less than 'Notify for Quantity Below' parameter of each product.

And can we show same message in product detail page More Information tab?

I have set Only X left Threshold as 15 in Store -> Configuration->Catalog->Inventory

I need to show That Qty left message message only if it is less than this value.

How this can be checked and show.

Please anyone suggest me in this?

Best Answer

Create a block class to your custom module named Vendor_Module to below path:

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

and add the below content to it:

<?php
namespace Vendor\Module\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 the below code to top of your list.phtml

$blockObj = $block->getLayout()->createBlock('Vendor\Module\Block\Product');

Then call the below block inside your foreach loop:

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

You can use the thing in your product details page.

Related Topic