Magento – Magento 2 How to get Controller Result in phtml file

collection;controllersmagento2phtml

I am submitting my form data to controller and getting filtered product collection using helper function.But Now I want that result data (from execute()) in my phtml file.Then I can display those filtered products.

Note : No need that data directly from controller to phtml, We can also use block or helper but the result collection I need in phtml file.

Can you help me on this?

Best Answer

You can create function in block example as below:

public function getEvents(){
        //get values of current page
        $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
        //get values of current limit
        $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 5;

        $collection = $this->_eventCollectionFactory->create();
        $collection->addFieldToFilter('is_active',1);
        $collection->setPageSize($pageSize);
        $collection->setCurPage($page);
        $collection->getSelect()->order('main_table.start_time asc');
        return $collection;     
    }

Using below code you can call this function in phtml file

$block->getEvents();

EDIT: How to get post data in block. you need to add below code in block

protected $request;
public function __construct(
    \Magento\Framework\App\Request\Http $request,
    ....
) {
   $this->request = $request;
}
public function getPostData()
{
  // you can use below code in any function       
  $postData =  $this->getRequest()->getParams();
}