how to call block method from magento 1 template
Solution 1
To create object for block in template (phmtl) file. Try the following code
$customBlock = $this->getLayout()->getBlock('block_name'); // You can use newsletter11 in that block_name
To call block function
echo $customBlock->test();
Solution 2
<?php echo $this->getLayout()
->createBlock('cms/block')
->setBlockId('seo-homepage')
->toHtml();
?>
Where seo-homepage is your static block identifier
Solution 3
this worked for me
$customBlock = $this->getLayout()->getBlockSingleton('block-class-name');
rramiii
Updated on June 22, 2022Comments
-
rramiii almost 2 years
I'm new to magento and always have issues.
For now, I managed to add subscribe popup message and want to add a child block to my main block.
Code:(my custom module is
My_Module
)<reference name="before_body_end"> <block type="newsletter/subscribe" name="newsletter_popup" as="newsletter_popup" template="popup/subscribe.phtml"> <block type="Module/popup_newsletter" name="newsletter11" /> </block> </reference name="before_body_end">
and in
subscribe.phtml
I try the following:var_dump($this->getChildHtml('newsletter11'))
but the result is:
string(0)""
I tried to load the block from template in this way also:
var_dump($this->getLayout()->createBlock('module/popup_newsletter'));
but the result is
boolean(false).
what I want to do is call a method from child block (
Newsletter.php
) and this out put some text, this block for now has these two methods:puplic function test(){ return 'this is test'; } public function _toHtml() { return test(); }
I can't see were is my mistake.
Can any one help me thankfully, I don't know if you need more code to post. Just let me know if you need
Thanks in advance.
update: config.xml file:
<?xml version="1.0" encoding="UTF-8"?> <config> <modules> <My_Module> <version>1.0.1</version> </My_Module> </modules> <global> <models> <my_module> <class>My_Module_Model</class> </my_module> </models> <helpers> <my_module> <class>My_Module_Helper</class> </my_module> </helpers> <blocks> <my_module> <class>My_Module_Block</class> </my_module> </blocks> </global> <frontend> <routers> <My_Module> <use>standard</use> <args> <module>My_Module</module> <frontName>my</frontName> </args> </My_Module> </routers> </frontend>
-
rramiii almost 10 yearsthank you for you response.. I tried this: var_dump($this->getLayout()->getBlock('module/popup_newsletter')); but the result is bool(false) .. I don't now why
-
MeenakshiSundaram R almost 10 yearsyou want to call one of the function in that block right?
-
rramiii almost 10 yearsdid't get you. can you give me example or apply it on code I posted
-
rramiii almost 10 yearsMy block is extending Mage_Core_Block_Abstract is that correct??
-
MeenakshiSundaram R almost 10 yearsLet us continue this discussion in chat.