3

I am trying to get all the in stock simple products of a configurable product in magento2.

Below code gets all in stock and out of stock products of configurable product, But I need only the in stock products

$configProduct = $this->_product->load($currentProduct->getId());
$_children = $configProduct->getTypeInstance()->getUsedProducts($configProduct);

How can we filter this by in stock?

5

You can use Model StockRegistry Magento\CatalogInventory\Model\StockRegistry $stockRegistry

Register a Block or Helper. My code example use Helper.

class Data
{
    protected $catalogProduct;
    protected $stockRegistry;
    public function __construct(
        \Magento\Catalog\Helper\Product $catalogProduct,
        \Magento\CatalogInventory\Model\StockRegistry $stockRegistry)
    {
        $this->stockRegistry = $stockRegistry;
        $this->catalogProduct = $catalogProduct;
    }

    /**
     * @param $product
     * @return \Magento\Catalog\Model\Product[]
     */
    public function getAllowProducts($product)
    {

            $skipSaleableCheck = $this->catalogProduct->getSkipSaleableCheck();

            $products = $skipSaleableCheck ?
                $product->getTypeInstance()->getUsedProducts($product, null) :
                $product->getTypeInstance()->getSalableUsedProducts($product, null);
        return $products;
    }

    public function getChildInStock($product)
    {
        $inStock = [];
        foreach ($this->getAllowProducts($product) as $_product) {
            $stockItem = $this->stockRegistry->getStockItem($_product->getId(), 1);
            $saleable = $stockItem->getIsInStock() && $this->verifyStock($stockItem);
            if($saleable){
                $inStock[] = $_product;
            }
        }
        return $inStock;
    }
}
0

use some children also

foreach($_children as $child)
{
   $childproduct= $this->_product->load($child->getId());
}

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.