Magento – Pass variables to block

With this post I will described various ways to pass variables to block.

1. Run time in PHTML file

$productId = 10;
$this->getChild('testblock')->setData("productId", $productId);
echo $this->getChildHtml('testpage', fales);

NOTE: second parameter ‘false’ is to tell, not to cache block.

2. Pass variables from a layout to a block
Yes, We can insert variable into a block from layout xml file as bellow,

<reference name="root">
   <block type="yourmodule/testblock" name="testpage">
        <action method="setData"><name>product_id</name><value>10</value></action>

Using the action tag with the method=”setData” attribute. Its child tags name and value to set variable and its value.
setData method of block is called when the system loads layout. name, value tags are parameters of setData method.

In block file you can access this by,

$productId = $this->getProductId(); 
$productId = $this->getData(‘product_id’);

3. Used in CMS page
we can put variables into a block by,

{{block type="yourmodule/testblock" product_id=10 template="module/yourmodule/bestproduct.phtml"}}

2 thoughts on “Magento – Pass variables to block

  1. Pingback: Magento – Pass variables to block | Kenneth Carnesi

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s