I have created one block inside my custom module but it's not working. My module is working fine but my block is not working when I call my block from footer.phtml file it shows 'Fatal error: Call to a member function setTemplate() on a non-object'. Actually I want to show some message in my frontend using my custom block.I have mentioned my code below
local/Monojit/Custom/controllers/IndexController.php
<?php
class Monojit_Custom_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout();
$block = $this->getLayout()->createBlock(
'Mage_Core_Block_Template',
'my_block_name_here',
array('template' => 'custom/test.phtml')
);
$this->getLayout()->getBlock('content')->append($block);
$this->renderLayout();
}
}
?>
local/Monojit/Custom/Block/Mycustomblock.php
<?php
class Monojit_Custom_Block_Mycustomblock extends Mage_Core_Block_Template
{
//public function _prepareLayout()
// {
// return parent::_prepareLayout();
// }
public function _construct() {
parent::_construct();
$this->setTemplate('custom/test.phtml');
}
public function getmessage()
{
$msg = "showing my custom block";
return $msg;
}
}
?>
local/Monojit/Custom/etc/config.xml
<config>
<global>
<modules>
<monojit_custom>
<version>0.1.0</version>
</monojit_custom>
</modules>
<blocks>
<custom>
<rewrite>
<custom>Monojit_Custom_Block_Mycustomblock</custom>
</rewrite>
</custom>
</blocks>
<helpers>
<custom>
<class>Monojit_Custom_Helper</class>
</custom>
</helpers>
</global>
<frontend>
<routers>
<custom>
<use>standard</use>
<args>
<module>Monojit_Custom</module>
<frontName>custom</frontName>
</args>
</custom>
</routers>
<layout>
<updates>
<custom>
<file>custom.xml</file>
</custom>
</updates>
</layout>
</frontend>
</config>
I have created one theme (copied modern theme) inside frontend/default/monojit Changed admin design configuration as well,created necessary folder as well inside skin.screenshot pic
design/frontend/default/monojit/template/custom/test.phtml
//want to fetch data from my block
<p>This is your custom block called programatically.</p>
localhost/magento/index.php/custom page shows my message correctly but when I call my block from footer.phtml page
<?php echo $this->getLayout()->createBlock('custom/mycustomblock')->setTemplate('custom/test.phtml')->toHtml(); ?>
It shows 'Fatal error: Call to a member function setTemplate() on a non-object' Do I need to create any layout.xml file? Please help me how can i fix my issue.thanks
Best Answer
Your block was not created, and createBlock return a non-object value. It happens because you don't specify custom namespace class prefix. Your block node in XML config should looks like
It means everything under custom namespace will be created with Monojit_Custom_Block prefix, so custom/mycustomblock => Monojit_Custom_Block_Mycustomblock.
But using createBlock is usually bad practice, it better to use layout files: