0

I need to get all the child products details like id, name, sizes attribute from a configurable product id in a product listing page(list.phtml) page.

    <?php
$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->getSku()."</br>"; //Child Product Sku    
    }

Above code is not working showing error Uncaught Error: Call to a member function getTypeInstance() on null

Please help me how to show virtual product information of configurable product in product listing page ?

3

First of: don't use the object manager directly. And your getting the error because current_product is not set on a product listing page.

If you look at list.phtml, you see a loop that iterates through the collection:

<?php foreach ($_productCollection as $_product): ?>
    // rendering of the product
<?php endforeach; ?>

Inside this loop you can use $_product->getTypeInstance() as expected. But you most likely want to do an extra check:

if ($_product->getTypeId() === 'configurable') {
    $productTypeInstance = $product->getTypeInstance();
    $usedProducts = $productTypeInstance->getUsedProducts($product);
    foreach ($usedProducts as $childProduct) {
        // ... do your stuff here ...
    }
}

Please note that this kind of logic in your template can become very heavy very quickly so be careful what you do and/or make clever use of caching. Although the getUsedProducts()-method has internal caching.

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.