2

Is there any way to call function defined in the app/code/Custom/Module/helpers/HelperClass.php inside the app/design/frontend/Custom/Theme/Magento_Theme/template/html/View.phtml in Magento 2?

I'm fairly new with magento 2, so I have no idea on how to achieve this.

1
  • does you get answer from my code or not? May 1 '19 at 14:01
2

To call the helper function into phtml file, you can use this code.

<?php
$helper = $this->helper('Custom\Module\Helper\HelperClass');?>
$helper->Yourfunction();
?>
0
2

You should not call helper directly in phtml.

You should provide helper instance dependency to the block that will renders the phtml and create a function in your block class that calls the helper and call that function in the phtml.

You should define it like below:

protected $helperData;


public function __construct(
     ....
    \{VendorName}\{ModuleName}\Helper\Data $helperData,
    ....
) {
    ....
    $this->helperData = $helperData;
    ....
}


public function doSomething()
{
    return $this->helperData->doSomething();
}

add below code in your phtml for calling helper:

$block->doSomething();
2
  • But block is located in the /app/code right? What if I want to call this $block->doSomething() inside the phtml of my custom theme which is located in /app/design? May 1 '19 at 13:05
  • Create an extension which should be use for your theme
    – Saphal Jha
    May 1 '19 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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