How to Pass Data from Controller to .phtml File in Magento 2.1

controllersmagento-2.1modelview

A page is submitted with the Voucher Number to check if it is valid, and if it is, then it the user moves forward in the process. How can I pass this value to the phtml to use again? Preferably I would like to pass it back as part of the model.

   public function execute()
    {
        // Get submitted voucher number
        $voucherNumber = $_POST['voucher-number'];

        // Validate the voucher number
        if($this->_objectManager->create('Hidden\Hidden\Helper\VoucherHelper')->validate($voucherNumber)){
            // Valid
            // ******** NEED TO RETURN $voucherNumber here
            return $this->resultPageFactory->create();
        }
        else {
            // Invalid
            return $this->_redirect('hidden/voucher');
        }
    }

I'm aware of this answer and this answer but both are related to Magento 1 and I want to make sure that they are still correct now. Further more these are related to blocks and I would think (although wrongly possibly) I can pass the model in from the controller action?

Best Answer

--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');

Related Topic