1

I have used below code to populate sub categories in other dropdown once the parent category is selected.

Used this code in my template file.

app/code/Vendor/Module/view/frontend/template/category.phtml

<div class="custom-dropdown">
        <select id="parent-cat" name="parent-cat" onchange="getChildrenList(this.value)">    
            <option value ="">- Please Select -</option>
             <option value ="3">Cat1</option>
             <option value ="4">Cat1</option>
        </select>
    </div> 
    <div class="custom-dropdown center-cus-drop">
        <select id="child-cat" name="child-cat" >    
            <option value ="">- sub category -</option>
        </select>
    </div>

  <script>  
  function getChildrenList(parentId) {
    var customurl = "<?php echo $this->getUrl().'frontname/category/childcategory' ?>";
    jQuery.ajax({
         url: customurl,
         type: "POST",
         data : 'category_id='+parentId,
         dataType: 'json',
         success : function(result) {
            console.log('result',result); 
         }
     });            
   }

 </script>

app/code/Vendor/Module/Controller/Category/Childcategory.php

  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 Childcategory extends Action
  {
    protected $categoryRepository;
    protected $resultJsonFactory;

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

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);
  }
 }

When the main category drop down changes my ajax call is hitting and i am getting the result. I need to append the result to the sub category drop down.

How this can be done using magento 2 standards? can anyone help me on this please? Thanks in advance

  • Did you find the answer? I am having same issue – embed0 Jan 17 at 9:26
  • @embed0, no not yet, i am waiting – jafar pinjar Jan 17 at 10:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.