Magento 2: How to get data from controller to block/view
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 should not passing data from Controller Action to View. Use block to for passing data to View (template engine).