Search code examples
magentopositionblock

Add new Block in the Controller and set this on the first position


I add a new Block in my Controller, this is working.

$this->loadLayout();
$cmsBlock = $this->getLayout()->createBlock('cms/block')->setBlockId('cms_block_fail');
$this->getLayout()->getBlock('content')->append($cmsBlock);
$this->renderLayout();

In the Layout.xml I set in the "content" structurblock an other contentblock.

<reference name="content">
    <block type="contactus/form" name="contact_us" template="contactus/contactus.phtml"/> 
</reference>

I want the CMS block before the contact_us block. In the Layout.xml I can use the parameters before and after. If I write after="-" the block will be set on the last position of the structure block "content", that's right? This is not working. How can I set this parameter with php in the Controller? Or other ideas?


Solution

  • $this->getLayout()->getBlock('content')->insert($cmsBlock,'contact_us'); should cause the $cmsBlock to be array_splice()ed into the content block's _sortedChildren() array ahead of the contact_us block.

    The logic is a bit abstruse but you can find more information about how this works in Mage_Core_Block_Abstract::insert() - note that append($block) is essentially an alias for insert($block,'',true).