Send data from the controller to phtml
-
16-10-2019 - |
Question
I have this controller:
...
public function insertAction() {
$something = 'testcase';
$this->loadLayout();
$this->_title($this->__("the title"));
$this->renderLayout();
}
...
I would like to access $something
in my .phtml document, how do I do this? (or to put it in another way: how can I access $something
in my .phtml file)
Solution
There are a couple of ways to do this.
Assign directly to the Block:
$block->assign($var);
or
$block->assign(array('myvar'=>'value','anothervar'=>true));
Then you can access it in the phtml file like this:
$this->myvar
Use the Mage registry:
Mage::register('custom_var', $var);
and then use it like:
$var = Mage::registry('custom_var');
OTHER TIPS
Your phtml must be rendered by a block. The block must have a name in the layout.
You can do this after calling $this->loadLayout();
$block = Mage::app()->getLayout()->getBlock('block_name_here')
if ($block){//check if block actually exists
$block->setSomething($something);
}
Then you can get the value in the phtml
file like
$value = $this->getSomething();
//or
$value = $this->getData('something');
In case you people missed there is one more way to get this done
using sessions
Mage::getSingleton('core/session')->setSomeSessionVar($data);// In the Controller
$data = Mage::getSingleton('core/session')->getSomeSessionVar(); // In the View;
If you're within your block controller.
class module_namespace_Block_example extends Mage_Core_Block_Template
{
protected $_var;
public function __construct(){
$this->_var = "something";
}
}
Then in your .phtml file
<?php
$variable = $this->_var;
echo $variable; // prints "something"
?>
<h1>You're inside your phtml file...... <?php echo $variable; //prints "something" ?></h1>
this is very easy to send data from controller to phtml file.
Step1:- Firstly create the Model class and extends from Varien_Object
class Namespace_Modulename_Model_Modelfilename extends Varien_Object
{
}
step2:- Now Open the contollerfile and put the code in the function.
$name='gaurav';
$this->loadLayout();
Mage::getSingleton('Modulename/Modelfilename')->setData('name',$name);
$this->renderLayout();
Step3:- Open the phtml file and put the code.
echo $name=Mage::getSingleton('Modulename/Modelfilename')->getData('name');
Output:- 'gaurav';