Categories
CMS Magento Mastering Development

Get quantity of simple products in configurable products on list.phtml

I’m trying to get the qty of simple products in configurable products in the list page and it works with this code inside the product collection foreach:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');


foreach ($_productCollection as $_product):

$configProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($_product->getId());

$_childrens = $configProduct->getTypeInstance()->getUsedProducts($configProduct);
 foreach ($_childrens as $child) {
  if ($StockState->getStockQty($child->getId(), $child->getStore()->getWebsiteId()) == 0) {
   echo "<span class='no-stock'>" . $child->getAttributeText('size') . "</span>";
  } else {
  echo "<span>" . $child->getAttributeText('size') . "</span>";
      }
}
endforeach;  

But this is very SLOW! how can I get the qty without using the objectManager?

how need to extend the ProductList class? How?

thank you in advance for your support

Leave a Reply

Your email address will not be published. Required fields are marked *