Magento - Passing Data Between a Controller and a Block

Magento - Passing data between a controller and a 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

  1. Create a simple Model class the inherits from Varien_Object

  2. In the controller, instantiate that object using the Mage::getSingleton('foo/bar')

  3. Set values on the Model using the magic getter/setters (you get these in objects that inherit from Varien_Object), or setData, etc.

  4. 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.

Pass data from block to view

For passing data from block to view

In block use

$this->setVariableName($value) or $this->assign(‘variableName’, $value)

In template use

$this->getVariableName() or $variableName respectively

For passing data from controller to block

It's not the responsibility of the controller to set variables for the view.

Controller set values from Models and block retrieves values from that model.

You can do this by:

  • Creating a model class that inherits from Varien_object
  • In the controller, instantiate that object using this code:

    $object = Mage::getSingleton('model')
    $object->setVar($value) or $object->setData('var', $value)
  • Later access the variable by

    $var = $object->getVar()

Hope you got what was needed :)

Other way to pass data from block to controller Magento

Good for you for wanting to adhere to best practices within Magento! The passing of data to controllers is pretty standard, however. If we look at how the product is added from a product page, we'll actually see the product ID in the form action URL's parameters:

http://domain.com/checkout/cart/add/uenc/uenc_value/product/45573/

...where 45573 is the product ID. Of course this can also be sent to the controller via a hidden input field, which I use all the time. Note that the above is the same as http://domain.com/checkout/cart/add/?uenc=uenc_value&product=45573 in Magento.

Another way of storing data for use in controllers for future use is setting data into a session. For posting data to a controller I wouldn't recommend this method but it's something to keep in mind:

$session = Mage::getSingleton('core/session');
$session->setMyValue(true);

We can then retrieve the data from my_value later just by instantiating the session. Good luck!

Magento How to pass data from a controller to a template?

In addition to asif's answer, we can also do :

In controller:

$layout = $this->getLayout();
$block = $layout->getBlock('block_name');
$block->setFeedback($feedback); //magic method

and then in phtml file:

$feedback = $this->getFeedback();

passing data to another controller

I am assuming from your question that you are redirecting from one controller to another and would like to pass query parameters along?

The syntax would be:

$params = array('key' => 'value');
$this->_redirect('frontname/controlller/action', array('_query' => $params));

EDIT

To answer the question in the comment on how to get these parameters from a template:

First off, I would advise not to do this, you should be recieving parameters in the controller. So, your custom controller should be responsible for receiving any parameters.

Regardless, the code in either situation is the same:

All parameters…

$this->getRequest()->getParams()

Single parameter…

$this->getRequest()->getParam('parameter_name')

How to pass variables from Controller to Block

Try this solution. Change this line

$this->getLayout()->getBlock('mdg_giftregistry.search.results')->setCustomerRegistries($results);

to

$this->getLayout()->getBlock('giftregistry.results')->setCustomerRegistries($results);

Passing data from layout to block controller using setData

When the layout rendering code encounters this

<block type="layout/carousel" name="featured_carousel">

It immediately instantiates the block. That means the block's __construct method is called before your setData method is called. So, at the time of construction, no data has been set, which is why your calls to var_dump return an empty array.

Also, immediately after being created, the block is added to the layout

#File: app/code/core/Mage/Core/Model/Layout.php
...
$block->setLayout($this);
...

When this happens, the block's _prepareLayout method is called.

#File: app/code/core/Mage/Core/Block/Abstract.php
public function setLayout(Mage_Core_Model_Layout $layout)
{
$this->_layout = $layout;
Mage::dispatchEvent('core_block_abstract_prepare_layout_before', array('block' => $this));
$this->_prepareLayout();
Mage::dispatchEvent('core_block_abstract_prepare_layout_after', array('block' => $this));
return $this;
}

So, this means that any data set in your layout update xml is still not available, even in _prepareLayout. Once the system is done creating the block, it moves on to the next XML node.

<action method="setData">
<name>filter_attribute</name>
<value>is_featured_product</value>
</action>

and calls the setData method. Now your block has its data set.

Try defining a _beforeToHtml method on your block and checking for data there. (Assuming your block is being rendered)

Best way to pass data from controller to template after form submit

Awesome!

One of the way to pass data from controller to any block or phtml is to use Magento register.

Controller: Set or register data using Mage::register('any string name', $data)

public function indexAction() {

$this->loadLayout();

$data['ta'] = $this->getRequest()->getPost('torque-action');
$data['tr'] = $this->getRequest()->getPost('torque-required');
$data['tm'] = $this->getRequest()->getPost('torque-metric');
Mage::register('t1', $data['ta']);
Mage::register('t2', $data['tr']);
Mage::register('t3', $data['tm']);

$this->renderLayout();
}

Phtml: Get registered data using Mage::registry('your string name')

$_ta = Mage::registry('t1'); //torque action
$_tr_max = Mage::registry('t2'); //torque required
$_tm = Mage::registry('t3'); //torque metric

Note: This is actually simple to use just beware on your typos.

Thanks!

Magento 2 Module Handling Displaying Data proccessed in Controller

What you are looking for is a Redirect result.

In your Post controller you can create the redirect object like so:

<?php
public function execute() {
$post = $this->getRequest()->getPostValue();
// handle and process data
// The data processed should be displayed in the Result page
$result = $this->resultRedirectFactory->create();
$result->setPath("path to your result controller", [$post, any_other_params]);
return $result;
}
?>

This will create the redirect result and will call the execute method of whatever controller route you passed as the first param of setPath and the array will be passed in with the url.



Related Topics



Leave a reply



Submit