1

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
9

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
    A much better approach, I can confirm this works in 2.2.1 – Dan Norris Dec 17 '17 at 17:13
  • 1
    and works in 2.2.2 too. – Alyas Feb 23 '18 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
    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. – Shahzaib Hayat Khan Dec 4 '17 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, privacy policy and cookie policy

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