Question

How do I pass data from the controller to my block file? Below is the code which I am using inside the controller.

 $this->_view->loadLayout();
  $this->_view->getLayout()
                 ->createBlock("Mymodule\Booking\Block\BookingList")
                 ->setTemplate("Mymodule_Booking::content/test.phtml")
                 ->toHtml();
Was it helpful?

Solution

You can do it like this:

using the block generator arguments (check vendor/magento/framework/View/Layout/Generator/Block.php and see what it does inside the createBlock() and inside it in $block->addData() method):

$block = $this->_view->getLayout()
   ->createBlock(
       'Mymodule\Booking\Block\BookingList'
       '<block_name>',
        ['data' => $data]
    );
$block->setTemplate("Mymodule_Booking::content/test.phtml")
$block->toHtml();

you can see an example of this kind of usage in vendor/magento/module-banner/Controller/Adminhtml/Banner/Widget/Chooser.php.

OR you can define a custom setter in your block class and pass the data like this:

$this->_view->getLayout()
   ->createBlock("Mymodule\Booking\Block\BookingList")
   ->setMyCustomData($data)
   ->setTemplate("Mymodule_Booking::content/test.phtml")
   ->toHtml();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top