Is there a way to pass a variable from controller to a phtml file without using registry? I tried this: Magento 2 pass data from Controller to Block and display in Template but it is not working.
5 Answers
Why would you want to use a registry ? Is there a reason beyond this ?
You need to pass variables threw controller and block depending on how the templates is defined.
For example :
Template definition
<block class="Magento\Framework\View\Element\Template"
name="magemastery.first.layout.example"
template="MageMastery_FirstLayout::example.phtml" />
Passing the variable
public function execute() {
/** @var Page $page */
$page = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
/** @var Template $block */
$block = $page->getLayout()->getBlock('magemastery.first.layout.example');
$block->setData('custom_parameter', 'Data from the Controller');
return $page;
}
Then in template : $block->getData('custom_parameter');
To get more details : https://magemastery.net/courses/magento-2-beginner/passing-data-from-controller-to-template
-
Thank you, this worked for me using magento 2.4.4-p2 Commented Oct 16, 2023 at 13:11
When you create your block with $block = $this->_view->getLayout()->createBlock('module\Block\Adminhtml\CustomBlock');
, you can pass data to it using the 3rd argument to the createBlock function. For example:
$block = $this->_view->getLayout()->createBlock('module\Block\Adminhtml\CustomBlock', 'block name', ['data' => ['MyData' => 'value']]);
The data will then be accessible to your block through the $data array that is passed to it's constructor.
-
for further guidance read this article for your understanding. magemastery.net/courses/magento-2-beginner/…– S.ShahCommented May 16, 2022 at 8:53
it's also possible by ajax call. By using that controller variable could be call in phtml file.
Phtml file
<div id ="Div_id"></div>
<script type="text/javascript">
require(['jquery', 'jquery/ui'],function($) {
jQuery(function($){
$(document).ready(function(){
var customurl = '<?= $block->getBaseUrl()."ultimatefaq/index/data";?>';
$.ajax({
url: customurl
type: 'POST',
dataType: 'json'
}).done(function( ControllerVariable )
{ jQuery("Div_id").append(ControllerVariable
});
});
});
});
Controller file
<?php
namespace vendor\module\Controller\Data;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Data extends Action
{
protected $_coreRegistry = null;
protected $request;
protected $resultPageFactory;
protected $layoutFactory;
public function __construct(
Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Framework\Registry $registry,
\Magento\Framework\View\LayoutFactory $layoutFactory
) {
$this->resultPageFactory = $resultPageFactory;
$this->layoutFactory = $layoutFactory;
parent::__construct($context);
}
/**
* To create controller function
* @return variable
*/
public function execute()
{
$data = "Controller Data that woulde be dispalyed on phtml";
$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$result = $resultJson->setData($data);
return $result;
}
}
I hope it will work perfectely!
You can do it with static variable like below.
Controller class.
<?php
namespace Vendorname\Modulename\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
protected $pageFactory;
protected $blockdata;
public function __construct(
Context $context,
PageFactory $pageFactory,
\Vendorname\Modulename\Block\Index\Index $blockdata
)
{
$this->pageFactory = $pageFactory;
$this->blockdata = $blockdata;
parent::__construct($context);
}
public function execute()
{ $page = $this->pageFactory->create();
//$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
//$collection = $productCollection->addAttributeToSelect('*')->load();
$collection = 'yourvariable';
$this->blockdata->setColl($collection);
return $page;
}
}
Your Block class would be like.
<?php
declare(strict_types=1);
namespace Vendorname\Modulename\Block\Index;
class Index extends \Magento\Framework\View\Element\Template
{
private static $coll;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
array $data = []
) {
parent::__construct($context, $data);
}
public function setColl($c)
{
self::$coll = $c;
}
public function getCustomdata()
{
$coll = self::$coll;
return $coll;
}
}
And In use in phtml file from Block.
<?php
echo $block->getCustomdata();
?>
I had to work on same requirement and i achieved as below.
Controller Class
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
private PageFactory $pageFactory;
private RequestInterface $request;
public function __construct(
Context $context,
PageFactory $pageFactory,
RequestInterface $request
) {
parent::__construct($context);
$this->pageFactory = $pageFactory;
$this->request = $request;
}
public function execute()
{
$this->request->setParams(['data1' => 'value1', 'data2' => 'value2']);
return $this->pageFactory->create();
}
}
Frontend Layout XML
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Vendor\Module\Block\Index" name="index" template="Vendor_Module::index.phtml" />
</referenceContainer>
</body>
Block Class
Vendor\Module\Block\Index.php
namespace Vendor\Module\Block;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
class Index extends Template
{
private RequestInterface $request;
public function __construct(
Context $context,
RequestInterface $request,
array $data = []
) {
parent::__construct($context, $data);
$this->request = $request;
}
public function getControllerData()
{
return $this->request;
}
}
In Index.phtml file
You can get Data as below
<?php
/* @var Vendor\Module\Block\Index $block */
$controllerData = $block->getControllerData();
print_r($controllerData->getParams());
Hope it helps!!