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?

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();
        }
     }
    }
?>
| improve this answer | |

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.