0

I am trying to get all categories with their levels of a product through it's ID in my controller which is overriding default magento controller.

Can I get product's category path url through it's id in controller ?

How can I do this?

  • which default controller you want to override – ASQ Sep 18 at 9:52
  • @ASQ I am overriding Magento/Catalog/Controller/Product/View.php – chanchal Sep 18 at 9:55
1

Try like this,

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        

$categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');

$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');

$productId = 10001; // YOUR PRODUCT ID
$product = $productRepository->getById($productId);

$categoryIds = $product->getCategoryIds();

$categories = $categoryCollection->create()
                                 ->addAttributeToSelect('*')
                                 ->addAttributeToFilter('entity_id', $categoryIds);

foreach ($categories as $category) {
    echo $category->getName() . '<br>';
}
  • The above code will work in controller ? – chanchal Sep 18 at 9:58
  • yes, it works.. – Arunprabakaran M Sep 18 at 10:00
0

Try below code :

protected $_productCollectionFactory;
protected $_categoryFactory;
protected $_productRepository;

public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\Catalog\Model\ProductRepository $productRepository,
    \Magento\Catalog\Model\CategoryFactory $categoryFactory,
    \Magento\Framework\ObjectManagerInterface $objectManager,

    ......... Add other depedencies

) {
    $this->_productRepository = $productRepository;
    $this->_categoryFactory = $categoryFactory;
    $this->_productCollectionFactory = $productCollectionFactory;
    $this->_objectManager = $objectManager;

    ......... Add other depedencies

}

public function execute()
{
    $mainProduct = $this->getProductById($productId);
    $categoryIds = $mainProduct->getCategoryIds();
    $result = [];

    for ($i=0; $i < count($categoryIds); $i++) {
        $eachCat = [
            "id" => $categoryIds[$i], 
            "name" => $this->getCategoryName($categoryIds[$i])
        ];

        array_push($result, $eachCat);
    }

    return $result;
}

public function getProductById($id)
{
    return $this->_productRepository->getById($id);
}

public function getCategoryName($categoryId)
{
    $category = $this->_objectManagerr->create('Magento\Catalog\Model\Category')->load($categoryId);
    return $category->getName();
}

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.