Magento – Magento 2: How to call helper function in Controller

helpermagento-2.1

How to call helper function in controller:-

I have use below code:-

class Index extends \Magento\Framework\App\Action\Action
{
    protected $helperData;

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

    public function execute()
    {
        $this->helperData-><functionName>();
        return;     
    }
}

this code give me error as below:-

Uncaught TypeError: Argument 2 passed to {Vendor}\{Module}\Controller\Callforprice\Index::__construct() must be an instance of {Vendor}\{Module}\Helper\Data, none given, called in

Best Answer

Code is correct. This happened to me many times. I have cleared /var/generation directory when altering constructor parameters.

Hope this helps.