Skip to content

magento 2.4 method stops working when moved from phtml template to php block class

I have a phtml template for my category page. The relevant code is:

// @var $block MagentoCatalogBlockCategoryView
$_category = $block->getCurrentCategory();
$_imgUrl = $block->getImage()->getUrl($_category);

I need to reuse this code in another template, so I thought about creating a block class in my custom module (app/code/Vendor/Category/Block/View.php) and put the relevant code there:

namespace VendorCategoryBlock;
class View extends MagentoFrameworkViewElementTemplate {
    protected $categoryView; 
    public function __construct(
        MagentoFrameworkViewElementTemplateContext $context,
        MagentoCatalogBlockCategoryView $categoryView,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->categoryView = $categoryView;
    }

    public function getCurrentCategoryUrl()
    {
        $_category       = $this->categoryView->getCurrentCategory(); // this works
        $_imgUrl         = $this->categoryView->getImage()->getUrl($_category); // this doesnt work
    }
}

My problem is that the first line works as expected. The second line works only in the phtml (it correctly gives me the image url), once I move it in the block file, it doesn’t work anymore (it gives me null). Any clue on why this happens and how to solve it?