--We can use \Magento\Framework\Registry in your Block or Controller.
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry = null;
...
$this->_coreRegistry = $registry;
...
$this->_coreRegistry->register('voucherNumber', $voucherNumber);
//We can get
$this->_coreRegistry->registry('voucherNumber');
--After loading layout, get the block and set values in Controller.
/**
* @var \Magento\Framework\App\ViewInterface $_view
*/
/**
* @return void
*/
public function execute()
{
$voucherNumber = 24566;
$this->_view->loadLayout();
$block = $this->_view->getLayout()->getBlock('your_block_name');
if($block) {
$block->setVoucherNumber($voucherNumber);
}
$this->_view->renderLayout();
}
--We can use setData() or getData() in our Block.
//In your Block:
public function getVoucherNumber()
{
if (!$this->hasData('voucherNumber')) {
$this->setData('voucherNumber', $voucherNumber);
}
return $this->getData('voucherNumber');
}
//In your template:
<?php $voucherNumber = $block->getVoucherNumber();?>
Sample: Pass model object via controller.
<?php
namespace Vendor\Module\Controller\Test;
class Index extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry;
/**
* @var \Magento\Framework\Controller\ResultFactory
*/
protected $_resultPageFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory,
\Magento\Framework\Registry $coreRegistry
)
{
$this->_coreRegistry = $coreRegistry;
$this->_resultPageFactory = $pageFactory;
parent::__construct($context);
}
public function execute()
{
//Get ID and create model
$entityId = $this->getRequest()->getParam('entity_id');
$model = $this->_objectManager->create('Vendor\Module\Model\VoucherEntity');
if($entityId) {
$model->load($entityId);
if(!$model->getId()) {
$this->messageManager->addError(__('This entity no longer exists.'));
/** \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/');
}
}
/** @var \Magento\Framework\View\Result\Page $resultPage */
$resultPage = $this->_resultPageFactory->create();
//Register model to use later in blocks
$this->_coreRegistry->register('voucher_entity', $model);
return $resultPage;
}
}
In your Block, you can get:$this->_coreRegistry->registry('voucher_entity')
;