Search code examples
magento-1.9configurable-product

Get number of swatches of an attribute that has a product


I have configurable products with a swatch attribute, in this case is color.

I need to know how many colors (the number) has a product, or maybe how many single products compose this configurable product.

As a matter of fact, I need to know when there is more than one color in a product.


Solution

  • Finally I found it, maybe it will help somebody in the future:

    $productAttributeOptions = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);
    
    //in this case the attribute color that I needed is in [0] position
    $available_colors = sizeof($productAttributeOptions[0]["values"]);
    
    if ($available_colors >1):
        //custom code
    endif;
    

    Edit: This solution works for one product, or at least for a few products, but if you need it in a list of products it is really slow to run this code in each of the products. Sometimes it drives to a timeout and closes the db connections, so the web crashes with an error.

    Finally I got a solution, maybe it is not the best one, but it is pretty fast compared to the one I was using before:

    $_idsForTheQuery = $_productCollection->getAllIds();
    
        $read = Mage::getSingleton('core/resource')->getConnection('core_read');
        $sql_query = "SELECT parent_id, COUNT(parent_id) AS colors FROM
                    (SELECT cpr.parent_id FROM `eav_attribute` a
                    LEFT JOIN `catalog_product_entity_int` cpei ON cpei.attribute_id=a.attribute_id
                    LEFT JOIN `catalog_product_relation` cpr ON cpr.child_id=cpei.entity_id
                    WHERE attribute_code = 'color' AND cpr.parent_id IN (".implode (", ", $_idsForTheQuery).") 
                    GROUP BY cpr.parent_id, cpei.value) colors 
                    GROUP BY parent_id";
    
        $results = $read->query($sql_query);
    
        $number_of_colors_by_id_array = array();
        foreach($results as $r)
        {
            $number_of_colors_by_id_array[$r["parent_id"]] = $r["colors"];
        }
    

    and then in the foreach loop of the products

    <?php if ($number_of_colors_by_id_array[$_product->getId()]>1): ?>
        <div class="aditional-colors-message">
            <?php echo __('more colors available'); ?>        
        </div>
    <?php endif; ?>