Magento – How to get available size based on color configurable product

configurable-productmagento-1.7magento-1.8product-attribute

I am trying to get the available size based on color

$attValConfig = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);

It is returning both color and size but I want color first after that sizes based on color.

foreach($attValConfig as $attValConfigSingle) {

   var_dump($attValConfigSingle["label"]);

   //Output Color and Size
}

Best Answer

You could get those options by getting the available child products and matching the option values like this:

//get all attributes
$configAttributesArray = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);

//filter so only color is left and select the values in the array
$configAttributesFilteredByColor = array_filter($configAttributesArray, function($v) { return $v['label'] == 'Color'; });
$configAttributesFilteredByColorValues = $configAttributesFilteredByColor[key($configAttributesFilteredByColor)]['values'];

//get the configurable product its childproducts

$childProducts = Mage::getModel('catalog/product_type_configurable')
    ->getUsedProducts(null,$product);

//loop the values, and the childproducts and match them
foreach($configAttributesFilteredByColorValues as $configAttributeValue){
    echo $configAttributeValue['label'] . '<br />';
    $value = $configAttributeValue['value_index'];
    foreach($childProducts as $childProduct){
        if($childProduct->getColor() == $value){
            echo $childProduct->getAttributeText('size') . '<br />';
        }
    }
}

If you are planning to use this on configurable products pages the price will not update anymore. If you are aiming for that functionality you should take a look at the function getJsonConfig in Mage_Catalog_Block_Product_View_Type_Configurable and refactor that to your needs.

Related Topic