Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally add blocks in magento layout

Is there a way to conditionally add a block in my magento layout based on whether the current customer is part of a group or not?

or would this be something better handled in the controller?

like image 701
veilig Avatar asked Aug 19 '11 14:08

veilig


1 Answers

It would be nice to use something like customer_logged_in and customer_logged_out but sadly that doesn't exist... yet.

Let's copy the same technique. To start with you'll need to make a module with this in the config:

<frontend>
    <events>
        <controller_action_layout_load_before>
            <observers>
                <customer_group_observer>
                    <class>CUSTOM_MODULE/observer</class>
                    <method>beforeLoadLayout</method>
                </customer_group_observer>
            </observers>
        </controller_action_layout_load_before>
    </events>
</frontend>

In the CUSTOM_MODULE_Model_Observer class add this method:

public function beforeLoadLayout($observer)
{
    $groupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
    $group = Mage::getModel('customer/group')->load($groupId);

    $observer->getEvent()->getLayout()->getUpdate()
       ->addHandle('customer_group_'.$group->getCode());
}

Now in layout files you can use the customer groups.

<layout>
    <customer_group_General>
        <reference name="content">
            <!-- Add some blocks -->
        </reference>
    </customer_group_General>
</layout>

Additionally, this method doesn't let you directly specify blocks per page but you can work around that. Here is an example that creates a new location for product pages only, on all other pages the update should have no effect and fail gracefully.

<layout>
    <catalog_product_view>
        <reference name="content">
            <block type="core/text_list" name="group_container" />
        </reference>
    </catalog_product_view>

    <customer_group_General>
        <reference name="group_container">
            <!-- Add some blocks -->
        </reference>
    </customer_group_General>
</layout>
like image 139
clockworkgeek Avatar answered Nov 12 '22 16:11

clockworkgeek