1

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

0

2 Answers 2

0

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.

1
  • Using this method, the block will inherit the unwanted dependencies from the controller as well. Not recommended.. Mar 23, 2021 at 7:22
0

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.