0

I want to get the category name of Parent Category as well as Child Category. For this, I am checking if Category == Parent Category and storing Category name into an array. And If Category is a Sub or Child category I want to store its name as ParentCategoryName / ChildCategoryName.

For example: If Parent Category = Engine and Sub Category = Engine Pump so Category Name = Engine / Engine Pump

Below is my code:

foreach ($categories as $category){
        $thAttribute = $category->getThNewAttribute();

        if(($category->getParentId($category))==2){
            $categoryName[$category->getThNewAttribute()] = $category->getName();
        }else{ 
            $categoryName[$category->getThNewAttribute()] = $category->getParentCategory($category)->getName()."/".$category->getName();
        }
 }

I am getting the correct Category Name for Parent Category but for Sub or Child Category I am getting below error.

No such entity with id = 0

Which step I am doing wrong?

1 Answer 1

0

Check below example to list of all subcategories of specific parent category using parent category ID using the repository.

First of all add CategoryRepository in construct:

<?php
    protected $categoryRepository;

    public function __construct(
        \Magento\Catalog\Model\CategoryRepository $categoryRepository
    ) {
        $this->categoryRepository = $categoryRepository;
    }
?>

Now you can use the following way:

<?php
    $categoryId = [YOUR_CATEGORY_ID];
    $category = $this->categoryRepository->get($categoryId);
    $subCategories = $category->getChildrenCategories();
    foreach($subCategories as $subCategory) {
        echo $subCategory->getName();

        /* For Sub Categories */
        if($subcategorie->hasChildren()) {
        $childCategoryObj = $this->categoryRepository->get($subCategory->getId());
        $childSubcategories = $childCategoryObj->getChildrenCategories();
        foreach($childSubcategories as $childSubcategory) {
            echo $childSubcategory->getName();
        }
     }
    }
?>
1
  • This line if($subcategorie->hasChildren()) { need to change if($subcategory->hasChildren()) {
    – Anees
    Commented Jul 18, 2022 at 2:26

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.