Posted on

how to get stock total for all simple products linked to a configurable product

everyone in my case I want to get all the qty total for all simple products linked to a specific configurable product I have to do the following (check my code below) but it returns “0” on total, can anyone help me, please?

if($product->getData(‘type_id’) == ‘simple’){
$stock_inventory = 0;
$sources = $this->sourceDataBySku->execute($product->getSku());
foreach ($sources as $source) {
$stock_inventory += $source[‘quantity’];
}

}
elseif ($product->getData(‘type_id’) == ‘configurable’){

$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$StockState = $objectManager->get(‘MagentoCatalogInventoryApiStockStateInterface’);
$stock_inventory = 0;
if($product->getTypeID() == ‘configurable’){
$productTypeInstance = $product->getTypeInstance();
$usedProducts = $productTypeInstance->getUsedProducts($product);
foreach ($usedProducts as $simple) {
$stock_inventory += $StockState->getStockQty($simple->getId(), $simple->getStore()->getWebsiteId());
}
}
}

Leave a Reply

Your email address will not be published.