I am working on year make like module in magento 2.In that module there will be dynamic drop down list in the front end. When some one will select a category from the first option the next option will be enabled and and it will display all its child categories.I am stucked in creating the dynamic drop down list.

1 Answer 1


You'll need a controller that you post the category ID to and it returns a JSON array of child category names and IDs with which to populate the subsequent dropdown.

Something like this should work:


namespace Your\Module\Controller\Index;

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;

class ChildCategories extends Action
    protected $categoryRepository;
    protected $resultJsonFactory;

    public function __construct(Context $context, CategoryRepositoryInterface $categoryRepository, JsonFactory $jsonFactory)
        $this->categoryRepository = $categoryRepository;
        $this->resultJsonFactory = $jsonFactory;


    public function execute()
        // get parent category
        $parentId = $this->getRequest()->getParam('category_id');
        /** @var Category $category */
        $category = $this->categoryRepository->get($parentId);

        $childrenData = [];

        foreach ($category->getChildrenCategories() as $childrenCategory) {
            $childrenData[] = [
                'name' => $childrenCategory->getName(),
                'id' => $childrenCategory->getId()

        return $this->resultJsonFactory->create()->setData($childrenData);
  • hi @Aron, how to call this controller in m2 standards? Also can you pls update code how to display in dropdown in template file Commented Dec 31, 2018 at 13:04

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.