Magento – Layout handle from attribute set

layout

I have 2 or 3 different bundle-type products. Generally they all appear the same in the catalog, with differing attribute sets showing/hiding available options.

It seems there will eventually be a bundle-type product with a vastly different template using a 1-column design as opposed to a 2-columns-right template. My first thought was to use custom layout xml, but all products added to this attribute set in the future will need the template.

Best Answer

By defining an observer to listen for controller_action_layout_load_before we are able to dynamically add layout handles on product pages based on the loaded product's attribute set:

<?php
class YourCompany_YourModule_Model_Observer
{
    public function addAttributeSetHandle(Varien_Event_Observer $observer)
    {
        $product = Mage::registry('current_product');
 
        /**
         * Return if it is not product page
         */
        if (!($product instanceof Mage_Catalog_Model_Product)) {
            return;
        }
 
        $attributeSet = Mage::getModel('eav/entity_attribute_set')->load($product->getAttributeSetId());
        /**
         * Convert attribute set name to alphanumeric + underscore string
         */
        $niceName = str_replace('-', '_', $product->formatUrlKey($attributeSet->getAttributeSetName()));
 
        /* @var $update Mage_Core_Model_Layout_Update */
        $update = $observer->getEvent()->getLayout()->getUpdate();
        $update->addHandle('PRODUCT_ATTRIBUTE_SET_' . $niceName);
    }
}

And now the following will work in a layout:

<PRODUCT_ATTRIBUTE_SET_shirts>
    <reference name="root">
      <action method="setTemplate"><template>page/view.phtml</template></action>
    </reference>
</PRODUCT_ATTRIBUTE_SET_shirts>

Code and examples sourced: http://magebase.com/magento-tutorials/creating-custom-layout-handles/