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?

enter image description here

Was it helpful?

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\StockStat‌​eInterface');
 $simpleSum = $simpleSum + floatVal($StockState->getStockQty($simple->getId(), $simple->getStore()->getWebsiteId()));
}
echo $simpleSum;

OTHER TIPS

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());
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top