How to fetch only immediate categories of a category in Hybris?

1k Views Asked by At

I only expect to fetch the direct children to the parent category. But instead I get all the children to that category by using getAllSubcategories method of DefaultCategoryService class.

Example: Say I have categories "Men" which has subcategories pants and tops. And tops has subcategories t-shirt and sweaters. Then when on the Men category I would expect to see only pants and tops. But what I am seeing in the latest hybris is all categories(pants, tops, t-shirt, sweaters etc. ) when clicking on Men.

Could someone please guide how to achieve that ? Or Do i need to write a flexible Query?

2

There are 2 best solutions below

0
On

Hi There is no OOB method to give you only immediate subcategories but yes we can use the above solution described by @Yoni

So you can create a simple method like this and use it when required.

  @Override
public List<CategoryData> getSubCategories(final String categoryCode)
{
    final CategoryModel category = defaultCategoryService.getCategoryForCode(categoryCode);
    if (category == null)
    {
        return Collections.emptyList();
    }
    final Collection<CategoryModel> subCategories = category.getCategories();
    return categoryConverter.convertAll(subCategories );
}
0
On

If you only want the direct children, you can make use of getCategories() on the category object model. This will only give you the direct children of that specific category

Where you are now calling getAllSubcategoriesForCategory(category), you can just go for category.getCategories()