I'm trying to generate on the fly a block by clicking on a button. My problem is that the blocks contained by the main block are not displayed.

Here is an example of something who fails :

mymodule.xml layout

<block type="mymodule/level1 name="level1" template="mymodule/level1.phtml">
    <block type="mymodule/level2" name="level2" template="mymodule/level1/level2.phtml">
        <block type="mymodule/level3" name="level3 template="mymodule/level1/level2/level3.phtml" />


<p>Level 1</p>
<?php echo $this->getChildHtml("level2"); ?>


<p>Level 2</p>
<?php echo $this->getChildHtml("level3"); ?>


<p>Level 3</p>

When I use this structure I correctly have all my three p elements.

But if I want to generate level1 block on the fly, I use an ajax call to AjaxController of my module :

echo $this->getLayout()->createBlock('mymodule/level1')->setTemplate('mymodule/level1.phtml')->toHtml();

I'm only getting the first level1 p element and the getChildHtml seems not called.

Can you help me to find another way to do get all the layout structure in my variable ?


The problem is, that the layout.xml creates three block, but you only one.

You need to create

level1 -> add child (create level 2 -> add child (create level 3))

So try this way:

$level1 = $this->getLayout()->createBlock('mymodule/level1')->setTemplate('mymodule/level1.phtml');

$level2 = $this->getLayout()->createBlock('mymodule/level2')->setTemplate('mymodule/level2.phtml');

$level3 = $this->getLayout()->createBlock('mymodule/level3')->setTemplate('mymodule/level3.phtml');


echo $level1->toHtml();
  • When I've tried this way, I get an error like addChild unkown method. Jun 4 '14 at 12:17

here is the way I manage to solve my problem. Thanks to Fabian Blechschmidt who help me to go on the right way.

$level1 = $this->getLayout()->createBlock('mymodule/level1')->setTemplate('mymodule/level1.phtml');
$level2 = $this->getLayout()->createBlock('mymodule/level1/level2')->setTemplate('mymodule/level1/level2.phtml');
$level3 = $this->getLayout()->createBlock('mymodule/level1/level2/level3')->setTemplate('mymodule/level1/level2/level3.phtml');

$level2->setChild("level3", $level3);
$level1->setChild("level2", $level2);

echo $level1->toHtml();
exit; // prevent "headers already sent error" in ajax

I saw your problem,block1c you mention in mymodule.xml is content block not structural block. First understand difference between content block and structural block.You can only call structural block directly and its child blocks called automatically.

example:$this->getChildhHtml('content').content is structural block.when you call this statement in template file then its child block automatically called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.