Really quick and simple question but I can't find a decent answer to this - What is the best way to pass data from a controller to a block in Magento.
Incase it makes a difference, I am loading the layout as follows:
$this->loadLayout(array('default', 'myModule_default')); $this->_initLayoutMessages('customer/session') ->_initLayoutMessages('catalog/session') ->renderLayout();
I should add, that I have been using the registry as follows:
In the controller:
Mage::register('data', $data);
In the block:
$data = Mage::registry('data');
Not sure if this is the best way to do it though.
At that time, we simply create new block inside Magento 2 store and call that block to the . phtml file where we want to display block. First, we need to call phtml file from static block using this code. In above code, you pass the category id with this code categories=”1,2,3″.
Block are responsible for rendering content (everything from frontend, backend, emails, and more). If content is being displayed somewhere chances are it is a block. controllers are responsible for processing all requests made via a url.
In PHTML file if call the function of block class that is provided in class attribute of tag. ReferenceBlock: ReferenceBlock is used when we want to use already existing block and want to put our block in that existing block. We use this if we want to add changes to phtml file of that block.
You don't.
In Magento's MVC approach, it's not the responsibility of the controller to set variables for the view (in Magento's case, the view is Layout and blocks). Controllers set values on Models, and then Blocks read from those same models. In Magento's view of the world, having a Block relying on the controller doing a specific thing is tight coupling, and should be avoided.
Your controller's job is to do certain things to Models, and then tell the system it's layout rendering time. That's it. It's your Layout/Blocks job to display an HTML page in a certain way depending on the state of the system's Models.
So, if I wanted to emulate traditional PHP MVC behaviors I'd
Create a simple Model class the inherits from Varien_Object
In the controller, instantiate that object using the Mage::getSingleton('foo/bar')
Set values on the Model using the magic getter/setters (you get these in objects that inherit from Varien_Object
), or setData
, etc.
In the Blocks, instantiate the Model again with a Mage::getSingleton('foo/bar')
and read the values back.
When you instantiate a Model with Mage::getSingleton(...)
Magento will instantiate the object as a singleton. So, if you re-instantiate an object (again with Mage::getSingleton('foo/bar')
) you're getting back the same object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With