Nov 9, 2012

Building Attribute Group Tree


Each product has a defined attribute set in Magento and which is set on creation of the product. Attribute sets consists of a number of attribute groups which in turn has a number of attributes.

Normally that is used only in admin, but I got a request to classify the attributes like that in a grid on frontend, which was a bit tricky. Below is the solution that I came up to.


$retValue = array();

/* @var $product Mage_Catalog_Model_Product  */
$product = Mage::getModel('catalog/product')->load(3224);

// Get the attribute set of the product
$attributeSetId = $product->getAttributeSetId();

// Get the attribute groups associated to the attribute set
$attributeGroups = Mage::getResourceModel('eav/entity_attribute_group_collection')
    ->setAttributeSetFilter($attributeSetId)
    ->load();


// Get the attributes of each group
foreach ($attributeGroups as $value) {
    $group['title'] = $value->getAttributeGroupName();

    $attributes = $product->getAttributes($value->getId());

    $attributeVal = array();

    foreach ($attributes as $attribute) {
        $att['title'] = $attribute->getFrontEndLabel();
        $attributeCode = $attribute->getAttributeCode();

        
        $data = $product->getData($attributeCode);
        if (!empty($data['values'])) {
            $attributeVal = $product->getAttributeText($attributeCode);
        }

        if (!empty($attributeVal)) {
            $att['value'] = $attributeVal;
            $group['value'][] = $att;
        }
    }

        $retValue[] = $group;
}

echo '<pre>';
var_dump($retValue);
echo '</pre>';

No comments:

Post a Comment