3

I want to show some extra data on product list page so I override the vendor\magento\module-catalog\Block\Product\ListProduct.php. For this I refer Add custom block on listing page : Magento2. It work.

But I need to call my helper function in my override block file. Created new file name ListProduct.php in app\code\Vendor\Module_Name\Block\Product:

namespace Vendor\Module_Name\Block\Product;
class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
{

    // I need to call my module helper function here:
    public function test()
    {

    }
}

How can I call my helper function inside this block file?
Thanks

Vigna S
  • 627
  • 7
  • 22

3 Answers3

3

You can call helper function by define helper class into construct method of class,

You can declare your helper classs in construct method like this,

 \Vendor\Mymodule\Helper\Data $dataHelper

And

 $this->dataHelper = $dataHelper;

Now you can call any functio of Data.php helper function like this,

$this->dataHelper->getFunction() and your function is working.

namespace Vendor\Module_Name\Block\Product;
 class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
 {
 public function __construct(
        \Magento\Catalog\Block\Product\Context $context,        
        \Magento\Framework\Data\Helper\PostHelper $postDataHelper,
        \Magento\Catalog\Model\Layer\Resolver $layerResolver,
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        \Vendor\Mymodule\Helper\Data $dataHelper,
        array $data = []
    ) {
        $this->dataHelper = $dataHelper;       
        parent::__construct(
            $context,
            $postDataHelper,
            $layerResolver,
            $categoryRepository,
            $urlHelper,
            $data
        );
    }

   public function test(){
        $this->dataHelper->getHelperFunction();
   }
}

Remove var folder and check

Rakesh Jesadiya
  • 42,221
  • 18
  • 132
  • 183
2

You should not do that.
but if you insist, make the block class that is rendered by the "other custom phtml" extend the block class that is rendered by the first phtml file.
Then you will have the method available in your second template and you can use it like $block->methodNameHere($paramsHere).

Marius
  • 197,939
  • 53
  • 422
  • 830
0

You must inject your Custom Helper \Custom\Module\Helper\Data

namespace Vendor\Module_Name\Block\Product;
class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
{
    protected $helper;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Custom\Module\Helper\Data $helper,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->helper = $helper;
    }

    // I need to call my module helper function here:
    public function test()
    {
        $this->helper->customMethod();
    }
}
Antoine Subit
  • 1,197
  • 1
  • 10
  • 19