Magento – Configurable products – Get product options in list.phtml

associate-productsattributesconfigurable-productmagento-1.9product-list

I'm having configurable products with 2 Attributes. Size and Color

It's been linked like this,

Size | Color
--------------------------------
 30  | Red (5 available), Green (1 available), Black (2 available)
 32  | Green (2 available)
 34  | Black (3 available), Blue (0 available)
 36  | Black (0 available)

Basically i'm trying to display available sizes in category list page (list.phtml)

like this

Size: 30 , 32 , 34, 36 (36 not bold coz it's not available)

so far i;ve tried this in list.phtml

$data = array();
    if($_product->isConfigurable()){
        $allProducts = $_product->getTypeInstance(true)->getUsedProducts(null, $_product);
        foreach ($allProducts as $subproduct) {
                $sizes[] = $subproduct->getAttributeText('waist');              
                    $data[] = array(
                        'name' => $subproduct->getAttributeText('waist'),
                        'qty' => $subproduct->getStockItem()->getQty()  
                    );              
        }
        if(count($data)>0) {
            sort($data);
            ?>
            <div>
            Size : <?php echo '<pre>'; print_r($data); echo '</pre>'; ?>
            </div>
            <?
        }
    }

It's working but it's giving me lot of duplicated values, coz every size is linked to one or more colors.

I can solve this by array sort & group, but i'm sure that it's not the proper way?

Coz i'm having more than 300 Configurable products and all associated to 25 + simple products.

Is there any way to achieve the same in magento way ??

Best Answer

You can try using something like this in your category page:

<?php if ($_product->isConfigurable()): ?>
<?php $attributes = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product); ?>
<?php foreach ($attributes as $attribute): ?>
    <?php if ($attribute['attribute_id'] == $yourSizeAttributeId): ?>
        <?php foreach($attribute['values'] as $option): ?>
            <?php echo $option['label'] ?>
        <?php endforeach ?>
    <?php endif ?>
<?php endforeach ?>

This will get you the list of the attributes that are used for configuring the product and for each attribute only the list of options that have an associated simple product.

Related Topic