cancel
Showing results for 
Search instead for 
Did you mean: 

Send data from controller to phtml

Send data from controller to phtml

how to send data from controller to phtml and how to access it ? 

2 REPLIES 2

Re: Send data from controller to phtml

Hello @shailesh_jadav 

 

Please follow this blog. You will find the solution to your problem.

 

If it helps then Click on Kudos and Accept as Solution.

 

Thanks,

Jignesh Chauhan

https://www.webcreta.com/blog

Re: Send data from controller to phtml

Hi @shailesh_jadav 

 

Please follow below steps to pass data from controller to phtml file:

1. create controller layout "frontname_controller_page_view.xml" file:

<block class="Magento\Framework\View\Element\Template"
       name="testing.first.layout.example"
       template="Frontname_Controller::example.phtml" />

2. The $blockvariable is now refer to a Templateclass instance. Use under controller function:

public function execute()
{
    /** @var Page $page */
    $page = $this->resultFactory->create(ResultFactory::TYPE_PAGE);

    /** @var Template $block */
    $block = $page->getLayout()->getBlock('testing.first.layout.example');
    $block->setData('custom_parameter', 'Data from the Controller');

    return $page;
}

3. phtml Template Logic example.phtml file:

<?php
use Magento\Framework\View\Element\Template;
/** @var Template $block */
?>
<h1>My First Template</h1>
<p>With Layout support</p>
<p><?= $block->getData('custom_parameter'); ?></p>

Image with result:
phtmlfile.png

 

Issue resolved ?
Please click on Kudos & Accept as Solution!

Problem solved? Click Accept as Solution!