Question

Is it possible to call a controller function in a block, if yes, please define how can i achieve that.

Was it helpful?

Solution

Please follow the below step to call the controller function in the block.

Step 1: Create a function in the controller file like below.

Vendor\Module\Controller\Index\ControllerName.php

public function getControllerFunction()
{
    return __('Controller Function');
}

After that call controller class in block construct and call controller function like below.

Vendor\Module\Block\BlockName.php

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Vendor\Module\Controller\Index\ControllerName $controller,
    array $data = []
) {
    $this->controller = $controller;
    parent::__construct($context, $data);
}

public function getControllerFunction()
{
    return $this->controller->getControllerFunction();
}

After that, if you want to call it in phtml file then call like below.

echo $block->getControllerFunction();die;

Don't forget to clear generated and cache.

Please check and let us know if you still facing any issues.

OTHER TIPS

A general practice in many frameworks is that if you want to reuse the same function in multiple places you write the function in a lightweight helper

If you want a function that is there in a controller and you want to reuse it in a block, it would be best to move that function in a helper class and inject the object of the helper class in the constructor of the controller as well as the block.

A helper class can also be called in a block template

$helper = $this->helper('{Vendor}\{Module}\Helper\Data::class');
$values = $helper->yourHelperMethod();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top