Reading list Switch to dark mode

    How to Display Left Quantity on Product Page in Magento 2

    Updated 9 August 2021

    “Hurry Up!! Only 5 Qty left in stock”

    This Type of Marketing strategy is use for prompt potential customers to convert before their products run out of stock.

    However, you also thought ” how to implement such a technique in Magento 2 product page? “

    And the result is to Display Left quantity in Magento 2 product page.

    As Magento 2.3 introduced the concept of salable quantity with the Magento 2 Multi-Source Inventory system (MSI), now Magento 2.3 and their above version make and use of it and add such this kind of notification on the frontend as shown below:

    Start your headless eCommerce
    now.
    Find out More
    Left Qty Show

    Salable quantity is the sum of all available products that allow you to manage multiple warehouses from one place and saves you from dead inventory or out of stock!

    Get product salable quantity in Magento 2 and display left quantity on the product page!

    Follow steps the below code to do so.

    1. Create registration.php at app/code/<vendor name>/<module name>/
    <?php
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Webkul_LeftQty',
        __DIR__
    );

    2. Create module.xml file at app/code/<vendor name>/<module name>/etc/

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Webkul_LeftQty" setup_version="1.0.0" schema_version="1.0.0"/>
    </config>

    3. Create routes.xml file at app/code/<vendor name>/<module name>/etc/frontend/

    <?xml version="1.0" ?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
        <router id="standard">
            <route frontName="leftqty" id="leftqty">
                <module name="Webkul_LeftQty"/>
            </route>
        </router>
    </config>

    4. Create LeftQty.php file at app/code/<vendor name>/<module name>/Block/ 

    <?php
    
    namespace Webkul\LeftQty\Block;
    
    use Magento\Catalog\Model\ProductFactory;
    use Magento\InventorySalesApi\Api\GetProductSalableQtyInterface;
    use Magento\InventorySalesApi\Api\StockResolverInterface;
    use Magento\Store\Model\StoreManagerInterface;
    use Magento\InventorySalesApi\Api\Data\SalesChannelInterface;
    
    /**
     * Class LeftQty
     * @package Webkul\LeftQty\Block
     */
    class LeftQty extends \Magento\Framework\View\Element\Template
    {
        /**
         * @var GetProductSalableQtyInterface
         */
        protected $salebleqty;
    
        /**
         * @var StockResolverInterface
         */
        protected $stockresolver;
    
        /**
         * @var StoreManagerInterface
         */
        protected $storemanager;
    
        /**
         * @var Http
         */
        protected $request;
    
        /**
         * @var ProductFactory
         */
        protected $product;
    
        /**
         * LeftQty constructor.
         * @param \Magento\Backend\Block\Template\Context $context
         * @param \Magento\Framework\App\Request\Http $request
         * @param ProductFactory $product
         * @param StoreManagerInterface $storemanager
         * @param GetProductSalableQtyInterface $salebleqty
         * @param StockResolverInterface $stockresolver
         * @param array $data
         */
        public function __construct(
            \Magento\Backend\Block\Template\Context $context,
            \Magento\Framework\App\Request\Http $request,
            ProductFactory $product,
            StoreManagerInterface $storemanager,
            GetProductSalableQtyInterface $salebleqty,
            StockResolverInterface $stockresolver,
            array $data = [])
        {
            $this->request = $request;
            $this->product = $product;
            $this->storemanager = $storemanager;
            $this->salebleqty = $salebleqty;
            $this->stockresolver = $stockresolver;
            parent::__construct($context, $data);
        }
    
        /**
         * @throws \Magento\Framework\Exception\LocalizedException
         * @throws \Magento\Framework\Exception\NoSuchEntityException
         */
        public function saleble()
        {
            $productId = $this->request->getParam('id');
            $websiteCode = $this->storemanager->getWebsite()->getCode();
            $stockDetails = $this->stockresolver->execute(SalesChannelInterface::TYPE_WEBSITE, $websiteCode);
            $stockId = $stockDetails->getStockId();
            $productDetails = $this->product->create()->load($productId);
            $sku = $productDetails->getSku();
            $proType = $productDetails->getTypeId();
    
            if ($proType != 'configurable' && $proType != 'bundle' && $proType != 'grouped') {
                $stockQty = $this->salebleqty->execute($sku, $stockId);
                return $stockQty;
            } else {
                return '';
            }
    
        }
    }

    5. Create catalog_product_view.xml file at app/code/<vendor name>/<module name>/view/frontend/layout/

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="alert.urls">
                <block class="Webkul\LeftQty\Block\LeftQty" name="catalog.product.view.leftqtyshow"
                       before="product.info.addtocart" template="Webkul_LeftQty::leftqty.phtml" cacheable="false"/>
            </referenceBlock>
        </body>
    </page>

    6. Create leftqty.phtml file at app/code/<vendor name>/<module name>/view/frontend/templates/

    <?= "<span>".__("Hurry Up!! Only %1 Qty left in stock",$block->saleble()) . "</span>";?>

    That’s all

    If any issue or doubt please feel free to mentioned in comment section.

    I would be happy to help.

    Happy Coding!!! 🙂

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home