2

I'm trying to get the quantity of the products in this file below, using $_product->getQty() but doesn't get, is returned NULL.

design/frontend/MyCompany/MyTheme/Magento_Catalog/templates/product/view/type/default.phtml

3 Answers 3

12

You can get Qty or other values like min qty by using that method.

echo $_product->getExtensionAttributes()->getStockItem()->getQty();

OR Complete Object Data

print_r($_product->getExtensionAttributes()->getStockItem()->getData());
2
  • 2
    A much better approach, I can confirm this works in 2.2.1
    – Dan Norris
    Commented Dec 17, 2017 at 17:13
  • 1
    and works in 2.2.2 too.
    – Alyas
    Commented Feb 23, 2018 at 18:06
2

You should be able to get with this piece​ of code below:

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
echo $StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
?>
1
  • 1
    BTW you shouldn't load it this way anywhere in file, use the same approach using proper design way ( Helper classes or anything like that ). Don't violate SOLID design principles. Commented Dec 4, 2017 at 8:44
0

I think this will be helpful for you-

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$product_qty = $product['quantity_and_stock_status']['qty'];

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.