0
$extensionStatus=$this->helper('Esparksinc\Extension\Helper\Data')->getConfig('Extension/general/enableDisable');

i am accesing this way but it gaves me a warning "The use of helpers in templates is discouraged. Use ViewModel instead" while checking code in magento coding standared.

1

You should not call $this->helper(...) in template file.

To get helper in template, you should add the helper instance to block dependency and create method in the block class to get the helper instance.

Example:

namespace Esparksinc\Extension\Block;

use Esparksinc\Extension\Helper\Data as Helper;
use Magento\Framework\View\Element\Template;

class YourBlock extends Template
{
    /**
     * @var Helper
     */
    private $helper;

    /**
     * @param Helper           $helper
     * @Param Template/Context $context
     */
    public function __construct(
        Helper $helper,
        Template\Context $context
    ) {
        $this->helper = $helper;

        parent::__construct($context);
    }

    /**
     * @return Helper
     */
    public function getHelper()
    {
        return $this->helper;
    }
}

To get the helper in template file:

// get helper instance
$helper = $block->getHelper();

// call public method inside helper
$extensionStatus = $helper->getConfig('Extension/general/enableDisable');
  • where is the ->getConfig defined? – usman Aug 25 at 19:13
  • I have updated the answer, it should be $helper->getConfig('Extension/general/enableDisable'); – Rendy Eko Prastiyo Aug 25 at 19:14
  • Thanks Alot .its working perfect .but what is in the case when we use view model for this. – usman Aug 25 at 19:25
  • I found this article interesting to answer your question: yireo.com/blog/2017-08-12-viewmodels-in-magento-2 (in When to use ViewModels? part) – Rendy Eko Prastiyo Aug 25 at 19:30

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.