0

I want to set the position of a block programmatically in Magento.

For example I wish that I can set the position of a block as:

  1. Below 'content' of product view page

  2. In the side bar (left/right)

  3. Before/after any other block.

Please suggest the way to do it.

Arvind Bhardwaj
  • 5,231
  • 5
  • 35
  • 49

1 Answers1

0

I have found a solution for this. You can set the block position dynamically using the observers. First of all create the Observer.php in <Namespace>/<Module>/Model directory. Write following code in this file:

class <Namespace>_<Module>_Model_Observer
{
    public function set_block($observer)
    {
        $action = $observer->getEvent()->getAction();
        $fullActionName = $action->getFullActionName();
        $position = 'right';
        $sub_position = 'before="cart_sidebar"';

        $myXml = '<reference name="'.$position.'">';
        $myXml .= '<block type="obc/obc" name="obc" template="obc/obc.phtml" '.$sub_position.' />';
        $myXml .= '</reference>';
        $layout = $observer->getEvent()->getLayout();
        if ($fullActionName=='catalog_product_view') {  //set any action name here
            $layout->getUpdate()->addUpdate($myXml);
            $layout->generateXml();
        }
    }
}

Now in config.xml write following lines to call the observer:

<events>
    <controller_action_layout_generate_blocks_before>
        <observers>
            <module_block_observer>
                <type>singleton</type>
                <class><Namespace>_<Module>_Model_Observer</class>
                <method>set_block</method>
            </module_block_observer>
        </observers>
    </controller_action_layout_generate_blocks_before>     
</events>

Now you can set the position of your block anywhere on the page using observer.

Arvind Bhardwaj
  • 5,231
  • 5
  • 35
  • 49