Making-Websites-With-October-CMS icon indicating copy to clipboard operation
Making-Websites-With-October-CMS copied to clipboard

How to create front-end dependent drop down in octobercms?

Open os-kingsley opened this issue 5 years ago • 5 comments

Good day, I am working on a front-end form. The form has cats and sub-cats. I have successfully been able to populate the cats select-box with data from the database using the code below

              `$this['items'] = Cat::where('parent_id',0)->pluck('cat_title', 'id');`

and in display

  `<select id="category" class="form-control">
    <option selected>Choose...</option>
   {% for key, item in items %}
    <option value={{ key }}> {{ item }}</option>
    {% endfor %}
      </select>`

The above works perfectly fine. The problem i have been faced with currently is how the populate the sub-cat select-box from the value of the cat select-box.

     ` <select id="subcategory" class="form-control">
    <option selected>Choose...</option>
     </select>`

I have looked up examples in laravel on dependent drop down using ajax and it looks straight forward but totally lost how to implement it in october. I will appreciate any help on this

os-kingsley avatar Mar 13 '19 15:03 os-kingsley

You need to add a data-request attribute to your category select and move rendering of your subcategory to a partial. Then you need the AJAX handler for category on your controller render the subcategory partial and replace the existing one on your form.

SeriousKen avatar Mar 14 '19 15:03 SeriousKen

You need to add a data-request attribute to your category select and move rendering of your subcategory to a partial. Then you need the AJAX handler for category on your controller render the subcategory partial and replace the existing one on your form.

I have made some good progress with your direction. Any ideas how to pass id parameter from category to subcategories. So when a category is selected only related subcategories drop down?

os-kingsley avatar Mar 17 '19 07:03 os-kingsley

You can get that from the request, for example:

function onChangeCategory()
{
    $category = post('category_id');
    // Build list of subcategories return result
}

SeriousKen avatar Mar 19 '19 09:03 SeriousKen

You can get that from the request, for example:

function onChangeCategory()
{
    $category = post('category_id');
    // Build list of subcategories return result
}

I have this

    `function onChangeCat()
     {
     $category = post('cat_id');
     $this['subs'] = Cat::whereHas('parent', function ($query) use($category) {
     $query->where('id','=', $category );
     })->pluck('cat_title', 'id');  
     }`

Am i missing something? I think what is left now is how to pass the id dynamically via data-request-data = "cat_ïd: '???'"

os-kingsley avatar Mar 19 '19 13:03 os-kingsley

Fixed it by adding name = "cat_title" to category select . No need for data-request-data Thanks

os-kingsley avatar Mar 19 '19 15:03 os-kingsley