Magento 2 – Get Associated Product Details Using Configurable Product ID

adminhtmlassociate-productsconfigurable-productmagento2product

I need to get all the child products details like id, name, color from a configurable product id in a custom phtml page.

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product

    $productTypeInstance = $product->getTypeInstance();

    $usedProducts = $productTypeInstance->getUsedProducts($product);

    echo $product->getId(); //Main configurable product ID
    echo $product->getName(); //Main Configurable Name

    foreach ($usedProducts  as $child) {
        echo $child->getId()."</br>"; //Child Product Id  
        echo $child->getName()."</br>"; //Child Product Name
    }

Used the above code. But error occurs for getUsedProducts. please help me to find a solution.

Best Answer

Will get the answer by this code itself afeter di:compile

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product

$productTypeInstance = $product->getTypeInstance();

$usedProducts = $productTypeInstance->getUsedProducts($product);

echo $product->getId(); //Main configurable product ID
echo $product->getName(); //Main Configurable Name

foreach ($usedProducts  as $child) {
    echo $child->getId()."</br>"; //Child Product Id  
    echo $child->getName()."</br>"; //Child Product Name
}
Related Topic