How can variables be passed to the block using the following methods?
In Magento, variables can be passed to a block instance in several ways, depending on how you create or access the block.
Passing variables From layout xml file to a block in Magento
To pass a variable from a Magento layout file, the easiest way is to include an action element like the following:
<block type="checkout/links" name="checkout_cart_link"> <action method="setData"><name>myvariable</name><value>myvalue</value></action> </block>
This action element makes a call to setData function (available in every Varien object), like if we make a call like the following in the php code:
Or the most common (using magic methods):
When you need to access a block from a controller in Magento, you first need to get the block instance from the layout. To do that, of course, the layout must be loaded first, so be sure this piece of code is called after the
// This can be included in an action controller to access the cart block $block = $this->getLayout()->getBlock('cart'); // And then, as usual: $block->setMyvariable('myvalue');
From one block to another
This is a similar situation than the previous one, being the only difference that we need to access the layout directly from the Magento application instance, so it would be something like:
// This can be included anywhere in your code $block = Mage::app()->getLayout()->getBlock('cart'); // And then, as usual: $block->setMyvariable('myvalue');
From an arbitrary location (for example, install/upgrade scripts, models)
As said before… from anywhere in the Magento code…
In which circumstances are each of the above methods more or less appropriate than others?
Probably the most common situations are, for each of the previous cases:
To pass data from a layout file. This is used mainly for block configuration values, like how many items per page will be rendered, how many columns, and so on.
To pass data from a controller. Probably the most used if we talk about backend programming. Not so used in frontend, where it would be seen like some dirty hack more than a standar way of passing data to a block.
Passing data from another block. It is probably the less convenient method, as you may encounter difficults if the block you are trying to access do not exists.
Passing data from a model. Common way of passing data from a model to a block is that the block pulls data from a model, not the other way.