Question

I am looking for the right flow of data of how Magento wants me to do it. I have some data which I want to pass to the view. How do I do this the right way?

I saw the following answer for Magento 1.x https://stackoverflow.com/a/4006908/2190322

Does this apply in the same way for Magento 2? Are there differences in the flow/implementation or is it the same? If there are some differences which are these and how do I implement them?

I also saw this question: https://magento.stackexchange.com/a/82376/5827 But it has no answer regarding to best practices, which I am looking for.

Was it helpful?

Solution

You should not passing data from Controller Action to View. Use block to for passing data to View (template engine).

OTHER TIPS

One approach is to use the registry so in your controller class you put it in the registry, and then in your block you can retrieve it.

<?php

namespace <Vendor>\<ModuleName>\Controller\Index;

use Magento\Framework\App\Action\Action;

class Index extends Action
{
    protected $_coreRegistry;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Registry $coreRegistry,
        \Magento\Framework\View\Result\PageFactory $pageFactory
    ) {
        $this->_coreRegistry = $coreRegistry;
        $this->_resultPageFactory = $pageFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->_coreRegistry->register('foo', 'bar');
        return $this->_resultPageFactory->create();
    }
}

Then in your block you can do;

<?php

namespace <Vendor>\<ModuleName>\Block;

use Magento\Framework\View\Element\Template;

class Moo extends Template
{
    protected $_coreRegistry;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Registry $coreRegistry,
        array $data = []
    ) {
        $this->_coreRegistry = $coreRegistry;
        parent::__construct($context, $data);
    }

    public function getFoo()
    {
        // will return 'bar'
        return $this->_coreRegistry->registry('foo');
    }
}

Obviously you need to get your block on the page in the first place but this should give you a good start.

You can do this way:

In your controller:

//\Magento\Framework\View\Result\PageFactory $pageFactory
$resultPage = $this->resultPageFactory->create();
// your.block.name is from your layout
$block = $resultPage->getLayout()->getBlock('your.block.name');
$block->setData('my_key', $data);

and now in template:

$data = $block->getData("my_key");

Hope this helps someone.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top