1

After get qty its show zero always Magento2

enter image description here

  • 1
    could you explain it more briefly ? – aravind Sep 5 '19 at 11:22
  • i need a qty of products i am using echo $_product->getQty(); to get but on all products its show 0 qty after getting – Junaid Ashfaq Sep 5 '19 at 11:24
  • in some products i have more then 0 qty but its shows 0 on product page – Junaid Ashfaq Sep 5 '19 at 11:25
  • i want to get stock of products – Junaid Ashfaq Sep 5 '19 at 11:28
  • have you tried my below code? – aravind Sep 5 '19 at 11:28
3

Try below way,

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

To get product qty in list page, for testing you can use objectmanager after finished testing create this method in helper/block and call that helper/block file from phtml(recommended).

$product_Id = $_product->getId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$stockInfo = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface')->getStockItem($product_Id);
$stockqty = (int)$stockInfo->getQty();
echo $stockqty;
| improve this answer | |
  • its working on just product detail page not on product listing page – Junaid Ashfaq Sep 5 '19 at 11:58
  • Fatal error: Uncaught Error: Call to a member function getQty() on null in /var/www/html/roykon23/app/design/frontend/Magento/roykon/Magento_Catalog/templates/product/list.phtml:172 Stack trace: #0 /var/www/html/roykon23/vendor/magento/framework/View/TemplateEngine/Php.php(59): – Junaid Ashfaq Sep 5 '19 at 11:59
  • try my updated answer..Instead of using object manager try calling it from custom block – aravind Sep 5 '19 at 12:03
  • yes its working thanks :) – Junaid Ashfaq Sep 5 '19 at 12:07
0

Try below code - in your phtml file

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

** For coding standard keep objectManager in helper class.

| improve this answer | |
  • this is shows 0 qty stock on all products on listing page – Junaid Ashfaq Sep 5 '19 at 12:04

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