18

Trying to develop something in magento 2. But, I didn't find how to call a Helper method in template(.phtml) file.

I want a replacement of below code:

$this->helper('modulename/helpername')->methodname();

If anyone knows please help me.

3
  • 1
    have you tried my answer? Dec 19, 2016 at 12:41
  • Hey, you should accept Marius's answer below. Sep 21, 2018 at 17:04
  • 1
    @seanbreeden Sorry, I have up voted, but forgotten to accept. Sep 28, 2018 at 9:11

9 Answers 9

38

You should not use helper calls directly in the template.
Have your helper instance provided as a dependency to the block that renders the template and create a method in your block that calls the helper and call that method in the template.

Have your block defined like this

protected $helperData;
public function __construct(
     ....
    \{Vendor}\{Module}\Helper\Data $helperData,
    ....
) {
    ....
    $this->helperData = $helperData;
    ....
}

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

Then you can call in your template $block->doSomething()

13
  • 2
    Can you please explain what would be the issue if we call helper in template directly without defining in dependency Dec 19, 2016 at 13:13
  • it's not a good practice. It introduces an undeclared dependency. If you want to do this properly you should only call in the template only methods from the block that renders it.
    – Marius
    Dec 19, 2016 at 13:45
  • 2
    Core magento developer also have called helper directly in phtml file Dec 19, 2016 at 15:11
  • 2
    That does not make it right. Maybe that part is not get refactored yet
    – Marius
    Dec 19, 2016 at 15:15
  • 1
    Short answer: yes. Long answer, you should not have a helper with 10 methods and all of them are needed for the same block. If that happens maybe you should think about refactoring your code to smaller blocks and templates.
    – Marius
    Dec 20, 2016 at 6:15
32

You have to use like this:

$helper = $this->helper('{Vendor}\{Module}\Helper\Data');
$values = $helper->YourHelperMethod();
7
8

You need to write whole class name in helper as below:

$this->helper('vendorename\modulename\Helper\helpername')

You can use it in phtml file using above code

2
  • like this will work on m2? Mar 6, 2019 at 14:21
  • $this is now deprecated in template logic Jul 22, 2019 at 12:38
2

I used this code in one of my module.

Change Custommodule to NameSpace ( Your company Name) change ReviewRating to ( Your Module Name)

In /var/www/html/magento2/app/code/Custommodule/ReviewRating/Block/HomehorizontalWidget.php

   <?php
namespace Custommodule\ReviewRating\Block;

class HomehorizontalWidget extends \Magento\Framework\View\Element\Template
{

protected $_helper;

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    array $data = [],
    \Custommodule\ReviewRating\Helper\Data $helper
) {
    parent::__construct($context, $data);

    $this->_helper = $helper;
}

public function getEnable(){
        return $this->_helper->getEnable();
    }

}

In /var/www/html/magento2/app/code/Custommodule/ReviewRating/view/frontend/templates/homehorizontalwidget.phtml

 <?php  echo $block->getEnable(); ?>

In /var/www/html/magento2/app/code/Custommodule/ReviewRating/Helper/Data.php

<?php 
namespace Custommodule\ReviewRating\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper { 

    /** * @var \Magento\Framework\App\Config\ScopeConfigInterfac 
        */ 
    protected $_scopeConfig; 
    CONST ENABLE = 'reviewrating/general/enable_module'; 


    public function __construct( \Magento\Framework\App\Helper\Context $context, 
            \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig ) {

             parent::__construct($context); $this->_scopeConfig = $scopeConfig;
    }

    public function getEnable(){
        return $this->_scopeConfig->getValue(self::ENABLE);
    }

}

In /var/www/html/magento2/app/code/Custommodule/ReviewRating/etc/adminhtml/system.xml

system configuration labels created here 
2

Try this code in your Block:

protected $helperData;
public function __construct(
     ....
    \{Vendor}\{Module}\Helper\Data $helperData,
    ....
) {
    ....
    $this->helperData = $helperData;
    ....
}

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

And in you template, you can call:

$helper = $block->getHelper();
1
$helper = $this->helper('{Vendor}\{Module}\Helper\Data::class');
$values = $helper->YourHelperMethod();
0

The best way is by injecting the helper in the block layout as shown in the magento documentation. This is called "Argument Injection"

Lets say this is your helper method:

app/code/Vendor/Module/Helpers/Data.php:

class Data extends AbstractHelper
{
    ...

    public function test($firstParam, $secondParam)
    {
        return "Test successfull p1: $firstParam, p2: $secondParam";
    }
}

Just add this inside your block:

<block class="Magento\Framework\View\Element\Template"
       name="example"
       template="Vendor_Module::mytemplate.phtml">
    
    <arguments>
        <argument name="foo_bar" xsi:type="helper" helper="Vendor\Module\Helper\Data::test">
            <param name="firstParam">firstValue123</param>
            <param name="secondParam">secondValue456</param>
        </argument>
    </arguments>
</block>

Then you can call the helper in the template:

/** @var mixed $helperMethodResult */
$helperMethodResult = $block->getData('foo_bar'); // or $block->getFooBar()

Now clear the cache php bin/magento cache:flush and reload the site where your block is getting loaded.

Output: Test successfull p1: firstValue123, p2: secondValue456

0

Method 1.

$helper= $this->helper('Vendor\Module\Helper\Data')->YourMethodName();

You can use above code directly in phtml file.

Method 2

Try this code in your Block:

protected $helperData;
public function __construct(
     ....
    \{Vendor}\{Module}\Helper\Data $helperData,
    ....
) {
    ....
    $this->helperData = $helperData;
    ....
}

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

And in you template, you can call:

$helper = $block->getHelper();
0

This solution is dirty and simple, but it works everywhere.

$objectManager = Magento\Framework\App\ObjectManager::getInstance();
$helper = $objectManager->create(Vendor\Module\Helper\Data::class);

Your Answer

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

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