Examples
mylayoutfile.xml
<layout>
<default>
<reference name="header">
<block type="mynamespace_mymodule/view" name="mynamespace_mymodule" output="toHtml" template="mymodule/html/view.phtml">
<action method="setTest"><param1>myparam1</param1><param2>myparam2</param2></action>
</block>
</reference>
</default>
</layout>
app/code/local/Mynamespace/Mymodule/Block/View.php
class Mynamespace_Mymodule_Block_View extends Mage_Core_Block_Template{
public $test = "before any params";
public function setTest($passedparam1,$passedparam2){
$this->test = $passedparam1 ." ". $passedparam2;
}
}
app/design/…/…/mymodule/html/view.phtml
<?php
echo "<pre>";
print_r($this->test); //myparam1 myparam2
echo"</pre>";
die();
Explanation
mylayoutfile is compiled in an update through your modules config.xml
the block class prefix of mynamespace_module is also defined within your modules config.xml
mynamespace_module/view is set as the block type and instantiated and the output file of view.phtml is set
an action takes place that calls the parent node block's method setTest passing two parameters with the value of myparam1 and myparam2.
inside of the setTest function the class parameter "test" is set to equal "myparam1 myparam2"
the template file app/design/…/…/mymodule/html/view.phtml is loaded and we echo the value of $this->test ($this refers to the earlier instantiated block class Mynamespace_mymodule_Block_View)
QUESTIONS
- What are some examples of use cases where this might be used?
- Can you pass anything other than a string? (Object,Array)?
- Do the automagical setters and getter methods work from inside a layout file?
- Can logic be used (if,then,foreach,else,etc)?
- Are there any scenarios where this method should not be used?
- Is there anything else I might be missing related to block instantiation from within a layout file?
- Is there anything else I might be missing related to actions from within a layout file?
Best Answer
setTitle
in catalog.xml.Anything can be passed. Arrays can be defined in layout XML:
Also, argument nodes can execute a helper method, the return value of which will be passed in as the value:
This would instantiate a helper & run a method:
Mage::helper('foo')->bar()
. The return value could therefore be anything you want. Additionally args can be passed to the helper in child nodes!Varien_Object
, so yes, though the setters are the only reasonable one to use.ifconfig
attribute which will callMage::getStoreConfigFlag()
with the provided argument and process the action if the config value is true.