Magento – Magento 2 : How to send data from controller to block and display on front end

magento-2.1magento2-dev-betamagento2-migration-tool

I have used the following code

<?php

namespace Inchoo\Helloworld\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Inchoo\Helloworld\Model\PostFactory;

class View extends Action
{


    protected $_modelPostFactory;


    public function __construct(
        Context $context,
        PostFactory $modelPostFactory
    ) {
        parent::__construct($context);
        $this->_modelPostFactory = $modelPostFactory;
    }

    public function execute()
    {

        $postModel = $this->_modelPostFactory->create();

        // Load the item with ID is 1
        $item = $postModel->load(1);
      //  var_dump($item->getData());

        // Get news collection
        $postCollection = $postModel->getCollection();
        // Load all data of collection
         var_dump($postCollection->getData());

    }
}

I have collected the database table field values using the above code. Now i need to send the to block. And need to display in front end

please help me

Best Answer

For sending data from controller to block, you can use registry

Controller

protected $_coreRegistry = null;

public function __construct(
      ....

        \Magento\Framework\Registry $_coreRegistry
    ) {
       .....
        $this->_coreRegistry = $_coreRegistry;
        ....
    }
   public function execute()
    {

        $postModel = $this->_modelPostFactory->create();

        // Load the item with ID is 1
        $item = $postModel->load(1);
      //  var_dump($item->getData());

        // Get news collection
        $postCollection = $postModel->getCollection();
        // Load all data of collection
         var_dump($postCollection->getData());
       $this->_coreRegistry->register('data_test', $postCollection);

    }

Block

 protected $_coreRegistry = null;


public function __construct(
      ....

        \Magento\Framework\Registry $_coreRegistry
    ) {
       .....
        $this->_coreRegistry = $_coreRegistry;
        ....
    }
   public function test()
    {
        $postCollection = $this->_coreRegistry->registry('data_test');
    }