0

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

1

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;
3
  • how to test for the status please , because the status i get is 0 or 1 not for stock it's for the product is it enabled or not – coding mv Dec 14 '20 at 12:59
  • I can provide you 2 ways here. Either find the sum of all simple products quantity and than calculate if they are greater or equal to 0, the second way us to get stock status of configurable product only. Than you can do what you think is best for you. Updating comment in a while – Arbab Ahmed Dec 14 '20 at 13:01
  • @code7 comment has been updated. Please mark this as right answer if your issue gets resolved using one of the 2 methods. Thanks – Arbab Ahmed Dec 14 '20 at 13:08
1

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());
?>
2
  • thank you for your reply , with this code i still get 0 in qty even if the product has the button Add to Cart – coding mv Dec 14 '20 at 12:37
  • Yes, This code only works for simple products. – David Duong Dec 22 '20 at 11:59

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.