1

In a custom template helper of com_content I need to get all children categories from specific category.

$categories = Joomla\CMS\Categories\Categories::getInstance('content');
$cat        = $categories->get($id);
return  $cat->getChildren();

But getInstance will be deprecated in J5:

@deprecated 5.0 Use the ComponentInterface to get the categories.

Please, what is the substitution method?

1 Answer 1

2

In CMS context you can get the component through the active application. The component may not necessarily support categories so it's a good idea to check if it implements the required interface:

$component = Joomla\CMS\Factory::getApplication()->bootComponent('content');

if (!$component instanceof Joomla\CMS\Categories\CategoryServiceInterface)
{
    // Component does not support categories. Bail here.
}

$categories = $component->getCategory();
$cat        = $categories->get($id);
return  $cat->getChildren();
2
  • Thanks Sharky, It's what I was looking for. I have a strange behavior: $categories = $component->getCategory()->get($catId)->getChildren(true); gives subcategories of $catId , but $categories = $component->getCategory(); $categories->get($catId)->getChildren(true); returns empty. It's right? I am doing something wrong?
    – Peli
    Apr 18, 2023 at 11:38
  • 1
    In the second snippet you do not write child categories to a variable. $categories is still an instance of Joomla\CMS\Categories\Categories. I updated the answer to include full code from your question, in case that makes it clearer. Essentially, nothing changes, except the first part.
    – Sharky
    Apr 18, 2023 at 13:50

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.