3

is there any chance how to get ALL third level categories available? I have searched whole internet and found only getting categories based on parent category but it doesnt return whole store 3rd level categories because in this situation I dont have one parent category, since I need all of them. Also I have found a lot of solutions using objectManager but I know you should avoid using it.

P.S. If you have an solution, it would be really nice to do it correctly - using CategoryRepository and definitely not using objectManager.

Thanks a lot!

3

Note that there is no CategoryRepository, but there is a CategoryListInterface that you can use in conjunction with a SearchCriteriaInterface

Something like this should work:

    /** @var \Magento\Catalog\Api\CategoryListInterface */
protected $categoryList;

/** @var \Magento\Framework\Api\SearchCriteriaBuilder */
protected $searchCriteriaBuilder;

/**
 * Constructor
 *
 * @param \Magento\Backend\App\Action\Context $context
 * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
 */
public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Catalog\Api\CategoryListInterface $categoryList,
    \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
) {
     parent::__construct($context);
     $this->categoryList = $categoryList;
     $this->searchCriteriaBuilder = $searchCriteriaBuilder;
}

/**
 * Redirect back to cadmart core
 *
 * @return \Magento\Framework\View\Result\Page
 */
public function execute(){
    $criteria = $this->searchCriteriaBuilder->addFilter('level', 3);
    $searchResult = $this->categoryList->getList($criteria);
    foreach ($searchResult->getItems() as $category) {
        echo($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.