I need to include a block in another block and launch it directly.
What I do now is this code in the first block
$this->getLayout()->createBlock('module/block');
then on that newly created block I have this
public function _prepareLayout()
{
$this->setTemplate('module/block.phtml');
echo $this->_toHtml();
}
This works fine, but having a echo in a the block model I don't really feel comfortable.
Is there any proper way to auto-launch this template at call of this block?
== EDIT ==
After trying the solution of @Keyul Shah it doesn't display anything.
So here is a more precise code of what I did.
I'm trying to call the block from a Admin Widget Form, so I put this in my XML:
<reference name="widget_instance_edit">
<block type="myModule/adminhtml_my_block" name="block_name" output="toHtml" template="myModule/toShow.phtml" />
</reference>
The module is called as everything in _prepareForm()
displays, but the phtml is not displayed.
If I try to do echo $this->_toHtml();
this time it has an error because it launches it before the parent.
=== FULL CODE ===
app/code/local/NameSpace/Module/Block/Adminhtml/Module/Images/Edit.php
class NameSpace_Module_Block_Adminhtml_Module_Images_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
// I want to call a specific block on top of the Edit Form
$this->getLayout()->createBlock('module/adminhtml_module_images_tagger');
// addFields stuff
...
}
}
app/code/local/NameSpace/Module/Block/Adminhtml/Module/Images/Tagger.php
class NameSpace_Module_Block_Adminhtml_Module_Images_Tagger extends Mage_Adminhtml_Block_Template
{
public function _prepareLayout()
{
// This works but is ugly and want to change it in a correct thing
$this->setTemplate('module/tagger.phtml');
echo $this->_toHtml();
}
}
The tagger.phtml doesn't matter.
=== Revision ===
After much more experience in Magento, I come back to this question and I realize that I was just on the wrong path.
The best way to do it is to create a block extending Mage_Adminhtml_Block_Widget_Form
, then simply call $this->setTemplate('path/to/your.phtml');
and then get inspired by the phtml report/grid/container.phtml
Best Answer
The better way is you can use via XML code.
In your
Layout.xml
file you can defileoutput
attribute. So do not do manually via code.The below example will show you how to write in xml.
When your Block called It will automatically return the html format.