veilig
veilig

Reputation: 5135

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?

Upvotes: 6

Views: 4081

Answers (2)

Flipmedia
Flipmedia

Reputation: 490

The following post will provide details the functionality your require: http://www.magentocommerce.com/boards/viewthread/83244/#t219147

Use customer_logged_in or customer_logged_out blocks in your layout files to add or remove elements, these blocks are called last.

No need to add additional extensions or code, this is built into Magento as standard.

Hope this helps, worked for me. Magento Version: 1.6+

Upvotes: 0

clockworkgeek
clockworkgeek

Reputation: 37700

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>

Upvotes: 16

Related Questions