I am creating an extension that will add dynamic content to different parts of page depends on selection. Admin user can add elements to left sidebar, right sidebar, before/after content, ...
So far I found one way of doing it: Define all 8 positions inside layout file, then check inside module block if user selected this specific position and display content if yes, otherwise skip it.
<default>
<reference name="right">
<block type="company/module" name="company_module_right" template="company/module.phtml" />
</reference>
</default>
<default>
<reference name="header">
<block type="company/module" name="company_module_header_before" template="company/module.phtml" before="-" />
</reference>
</default>
....
This would work fine, but it is not perfect solution because I will need to load the same block and go through the same collection 8 times, each time for each position to check if user selected this section to inject elements into.
I was thinking about using observer:
<controller_action_layout_load_before>
<observers>
<inject_content>
<type>singleton</type>
<class>company_module/observer</class>
<method>addBlock</method>
</inject_content>
</observers>
</controller_action_layout_load_before>
Observer.php:
public function addBlock(Varien_Event_Observer $observer)
{
$layout = Mage::getSingleton('core/layout');
$collection = Mage::getModel('company_module/blocks')->getCollection();
foreach($collection as $col){
$content = $layout->getBlock($col->getData('parentBlockName'));
$newBlock = $layout->createBlock('core/template', $col->getData('injectedBlockName'));
$newBlock->setTemplate('company_module/blocks.phtml');
$content->append($newBlock);
}
}
But $layout->getBlock('content')
or $layout->getBlock('left')
or other blocks always return false. I tried also controller_action_layout_load_before
, in this way it won't return false but it also won't inject block. Any idea how to make this work?