how to get product quantity in magento 2.3 in phtml file
Question
I am using Magento 2.3 , in my case I want to test if a product has a quantity greater than or equal to 0 in the list of all product page, to add a message a customer, but I wonder how to get it, for now I can get all products and I can display the message image for all the product without test if quantity equal or grater than 0
Can anyone help me to have this test please in the product page?
La solution
You can't get the quantity for Configurable Product. It's a parent product you can only get it's stock status i.e "in_stock" or "out_of_stock".
Simple products are the ones having actual quantities e.g no of Small Product, no of Medium Products, etc
To check if a configurable is in stock or not, use this code.
if($_product->isAvailable()) {
// in stock
} else {
// out of stock
}
To get the sum of all simple products
$simpleSum = 0;
foreach ($_product->getTypeInstance(true)->getUsedProducts ( null, $_product) as $simple) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$simpleSum = $simpleSum + floatVal($StockState->getStockQty($simple->getId(), $simple->getStore()->getWebsiteId()));
}
echo $simpleSum;
Autres conseils
You can try this code:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
echo $StockState->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId());
?>