Google+

Pages

Sunday, July 6, 2014

Magento: Set page layout on specific pages programmatically

If you want to set page layout on specific pages programmatically; for example you need to change layout from 1column.phtml to 2columns-left.phtml in some condition or so, then you need to create a simple module for it.

Steps to do so are given below:


Under app/etc/modules folder create your module's definition file (Package_Module.xml) and put this code in it:

<?xml version="1.0"?>
<config>
    <modules>
        <Package_Module>
            <codePool>local</codePool>
            <active>true</active>
        </Package_Module>
    </modules>
</config>
 
Now create config.xml file under 
app/code/local/Your/Module/etc folder and put this code in it:
 
<?xml version="1.0"?>
<config>
    <modules>
        <Package_Module>
            <version>0.1.0</version>
        </Package_Module>
    </modules> 
    <global> 
        <models>
            <module>
                <class>Package_Module_Model</class>
            </module>
        </models>
        <events> 
            <controller_action_layout_generate_blocks_after>
                <observers>
                    <any_unique_name>
                        <type>singleton</type>
                        <class>Module/Observer</class>
                        <method>controllerActionLayoutGenerateBlocksAfter</method>
                    </any_unique_name>
                </observers>
            </controller_action_layout_generate_blocks_after>
        </events>
    </global>
</config>
 
Now create Observer.php under app/code/local/Your/Module/Model folder and put this 
code in it:
 
<?php
class Package_Module_Model_Observer
{
    public function controllerActionLayoutGenerateBlocksAfter ($observer)
    {
        $controller = $observer->getAction();

        if ($controller->getFullActionName() == 'catalog_product_view') {
            $layout = $controller->getLayout();
            $rootBlock = $layout->getBlock('root');

            if (Mage::getSingleton('customer/session')->isLoggedIn()) {
                $rootBlock->setTemplate('page/1-column.html');
            } else {
                $rootBlock->setTemplate('page/2-columns.html');
            }
        }
    }
}
 
That's it. Cheers.. :)