25

How to get stock quantity of each product in list.phtml in Magento 2 ?

45

Add bellow code in your list.phtml file

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
    echo $StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
?>

OR

<?php
   $stockItem = $product->getExtensionAttributes()->getStockItem();
   print_r($stockItem->getQty()); 
?>
  • 1
    For some reason, running this in a cron job always returns '0' – Giel Berkers Apr 18 '16 at 15:26
  • 7
    Please use DI instead of ObjectManager directly! – Matthias Kleine Jun 14 '17 at 12:47
  • 5
    Never use code like this directly. Use constructor DI instead. – Jisse Reitsma Jun 19 '17 at 7:30
  • 1
    @WackGet devdocs.magento.com/guides/v2.3/extension-dev-guide/… - "Magento prohibits the direct use of the ObjectManager in your code because it hides the real dependencies of a class. See usage rules." Standards are there for a reason, developers should respect that. – Tisch Aug 2 at 15:00
  • 1
    @Tisch There are plenty of cases where using ObjectManager directly is fine. Standalone scripts, product feeds, cron jobs, etc.; all fine. From your own link, Magento states: "In a global scope, like in fixtures of integration tests, you can use the object manager." Don't just blindy parrot stuff when the reality is far more nuanced. – WackGet Oct 18 at 17:28
13

Like some comments have mentioned, you want to use dependency injection. Do not use the object manager; in other words, do not do what any of the other responses state. The following technique can be applied anywhere. For Blocks, set the class to your class in layout XML, which extends the original, and inject the right information.

Inject the StockRegistryInterface interface where you need access:

/**
 * @var \Magento\CatalogInventory\Api\StockRegistryInterface
 */
private $stockRegistry;

/**
 * Constructor for DI.
 *
 * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
 */
public function __construct(
    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
) {
    $this->stockRegistry = $stockRegistry;
}

/**
 * Get the product stock data and methods.
 *
 * @return \Magento\CatalogInventory\Api\StockRegistryInterface
 */
public function getStockRegistry()
{
    return $this->stockRegistry;
}

To use it somewhere:

/** @var \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry */
$stockRegistry = [$this|$block]->getStockRegistry();

/** @var \Magento\Catalog\Model\Product $product */
$product = [Grab Product instance however you want. This is up to you.]

// Get stock data for given product.
$productStock = $stockRegistry->getStockItem($product->getId());

// Get quantity of product.
$productQty = $productStock->getQty();

For reference, Magento2 uses this exact interface all over the catalog when it comes to retrieving product stock information.

Note that anything within square brackets needs to be modified.

  • 3
    This should be marked as the correct answer. Although I haven't tested it (yet) it follows conventions. – Daan van den Bergh Aug 9 '18 at 11:27
  • 3
    I've tested it, and this is the correct way to do this. using the object manager is a no-no. – circlesix Aug 30 '18 at 15:16
  • 2
    Allways +1 for best practices! – Akif Jan 9 at 22:18
  • 2
    This should be the accepted answer as StockRegistryInterface works on every case, not the StockStateInterface. – Amrit Pal Singh Jun 28 at 6:33
  • 1
    Agreed, this should be the accepted answer. – Tisch Aug 21 at 9:52
12

How to get stock quantity of each product in Magento 2

for controller or block inject \Magento\CatalogInventory\Api\StockStateInterface

 public function __construct(
    \Magento\CatalogInventory\Api\StockStateInterface $stockItem
   )
  {
    $this->stockItem = $stockItem;
  }

and then use getStockQty function to get qty

 $this->stockItem->getStockQty($product->getId(), $product->getStore()->getWebsiteId());

if you want to get quantity in .phtml file then use

 <?php 
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
 echo $StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
?>
  • returning qty 0 for me even though i have qty 30 – jafar pinjar Nov 16 '18 at 10:30
  • @jafarpinjar found out today this also factors status - if disabled returns 0 - I can't decide if this is a good thing or not... – Dominic Xigen Jul 7 at 0:11
4

Below script will helpful to get the product stock qty, min qty and stock details in magento2.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productStockObj = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface')->getStockItem($productId);
print_r($productStockObj->getData());
0

If you want to $productobj after saving product from backend side so you can easily use catalog_product_save_after event.

I am assuming that you already know how to create a module in M2.

Right now you have to need develop new module for M2

Then Create this events.xml file in below path

app\code\YOUR_NAMESPACE\YOURMODULE\etc\adminhtml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_save_after">
        <observer name="test_name" instance="YOUR_NAMESPACE\YOUR_MODULENAME\Observer\Productsaveafter" />
    </event>
</config>

And Create your observer file Productsaveafter.php in below path

app\code\YOUR_NAMESPACE\YOURMODULE\Observer\

<?php

namespace YOURNAMESPACE\YOURMODULENAME\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
        $id = $product->getId(); //Get Product Id

        //Get Quantity
        $stockItem = $product->getExtensionAttributes()->getStockItem();
        $stockData = $stockItem->getQty();
        // Get new Qty
        $_vendor_qty = $product->getVendorQty();
        $_on_hand_qty = $product->getOnHandQty();
        $totalQty = $_vendor_qty+$_on_hand_qty; //Add New Qty


        $stockItem->setQty($totalQty); //Set New Qty to Main Qty
        $stockItem->save();

    }   
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.