3

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.

2
  • already asked on the same type of questions on your different Question
    – Amit Bera
    Feb 20, 2019 at 14:28
  • magento.stackexchange.com/q/262467/4564 .See , you already posted the same type of question.On your question, you already have given the answer
    – Amit Bera
    Feb 20, 2019 at 14:29

1 Answer 1

4

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 and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.