Magento customer group layout handle

It is a good idea to create a new layout handle in Magento when we need to be able to easily customize styling of pages or enable/disable specific blocks for the customer groups. Here is how.

This can be achived by observing controller_action_layout_load_before event. Define in your module’s config.xml following nodes:

<events>
    <controller_action_layout_load_before>
        <observers>
            <customer_group_handle>
                <class>module/observer</class>
                <method>addCustomerGroupHandle</method>
            </customer_group_handle>
        </observers>
    </controller_action_layout_load_before>
</events>

Next we need to implement addCustomerGroupHandle method in you module Model/Observer.php file. It will look like:

public function addCustomerGroupHandle(Varien_Event_Observer $observer)
{
    if (Mage::helper('customer')->isLoggedIn()) {
        /** @var $update Mage_Core_Model_Layout_Update */
        $update = $observer->getEvent()->getLayout()->getUpdate();
        $groupId = Mage::helper('customer')->getCustomer()->getGroupId();
        $groupName = Mage::getModel('customer/group')->load($groupId)->getCode();
        $update->addHandle('customer_group_' . str_replace(' ', '_', strtolower($groupName)));
    }

    return $this;
}

Here we are replacing spaces with underscore, because spaces are not valid in xml nodes. Pay attention if you have any other invalid characters in the group names. You need to replace or remove them before adding layout handle.
When we finished with adding a new handle, we can use it in local.xml or any other layout file:

<?xml version="1.0" encoding="UTF-8"?>
<layout>
    <customer_group_wholesale>
        <reference name="head">
            <action method="addItem"><type>skin_css</type><name>css/groups/wholesale.css</name></action>
        </reference>
    </customer_group_wholesale>
</layout>

Hope this article has useful insight on customizing layouts for groups of customers. I will be happy to hear any comments on how you applied this in your development.