Search code examples
magentovariableswidgetblock

Passing variable to Magento widget


I'm trying to pass a variable using setData to a box containing a widget with this:

$this->getChild('my_box')->setData('myvar', '123');
echo $this->getChildHtml('my_box');

or this:

echo $this->getChild('my_box')->setData('myvar', '123')->toHtml();

The "my_box" is the block linked with the widget, it's positioned in the footer and defined in local.xml:

<reference name="footer">
    <block type="core/text_list" name="my_box" as="my_box" translate="label">
        <label>My Box</label>
    </block>
</reference>

But if I try to retrieve the value in the widget with any of these methods:

echo $this->getData('myvar');
echo $this->getMyVar();
echo $this->myvar;

there is no return value, any suggestion?


Solution

  • Outside of a rewrite, "core/text_list" is an instance of Mage_Core_Block_Text_List (link) and would not have a template for you to call your code.

    You can verify that the basic functionality is working, though:

    $my_box = $this->getChild('my_box')->setData('myvar','123'); //if no error, my_box exists!
    
    echo get_class($my_box); //Mage_Core_Block_Text_List
    
    var_dump($my_box->debug()); //array() including 'myvar' => '123'
    
    echo $my_box->getData('myvar')` //correct
    echo $my_box->myvar //works, but unconventional
    echo $my_box->getMyVar() //will not access the property you set; rather...
    echo $my_box->getMyvar() //will work
    

    For other fun, you can set properties via layout XML:

    <reference name="footer">
        <block type="core/text_list" name="my_box" as="my_box" translate="label">
            <label>My Box</label>
            <action method="setMyvar">
                <arbitrary>123</arbitrary>
            </action>
            <!-- or <action method="setDatar">
                <name>myvar</name>
                <val>123</arbitrary>
            </action> -->
        </block>
    </reference>
    

    Also, do be aware the the footer block is permanently cached in the block_html cache by default.