2

This is my Vendor/Module/Block/BlockFile.php

<?php

namespace Vendor\Module\Block;

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

   public function getId()
  {
    return $this->getData('category_id');
  }

}

For now I'm getting category ID.

I need to get category name by ID using dependency injection.

1

Try this:

class CategoryList extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Catalog\Api\CategoryRepositoryInterface
     */
    private $categoryRepository;

    /**
     * CategoryList constructor.
     *
     * @param \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository
     */
    public function __construct(
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository
    ) {
        $this->categoryRepository = $categoryRepository;
    }

    /**
     * @param int $id
     * @param null $storeId
     * @return string
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    protected function getCategoryNameById($id, $storeId = null)
    {
        $categoryInstance = $this->categoryRepository->get($id, $storeId);

        return $categoryInstance->getName();
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->getData('category_id');
    }

    /**
     * @return string
     */
    public function getCategoryName()
    {
        try {
            return $this->getCategoryNameById($this->getId());
        } catch (\Magento\Framework\Exception\NoSuchEntityException $exception) {
            return 'Unknown Category';
        } 
    }
}

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.