Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a grouped select box using simple_form?

I'm using simple_form gem for creating Rails forms. http://github.com/plataformatec/simple_form

All is great, except how do I create a grouped select box? Can't find it in the docs or by google-ing.

like image 454
Swartz Avatar asked Oct 27 '10 20:10

Swartz


2 Answers

The question is old but it's the top result for "simple_form grouped select" google search anyway so I figured the next reader might benefit from a few creative ways to create these with the latest simple_form (taken from tests, which are always the best documentation indeed)

<%= f.input :author,
 :as => :grouped_select,
 :collection => [['Authors', ['Jose', 'Carlos']], ['General', ['Bob', 'John']]],
 :group_method => :last %>

<%= f.input :author,
 :as => :grouped_select,
 :collection => Proc.new { [['Authors', ['Jose', 'Carlos']], ['General', ['Bob', 'John']]] },
 :group_method => :last %>

<%= f.input :author,
 :as => :grouped_select,
 :collection => { ['Jose', 'Carlos'] => 'Authors' },
 :group_method => :first,
 :group_label_method => :last %>

<%= f.input :author,
 :as => :grouped_select,
 :collection => { 'Authors' => ['Jose', 'Carlos'] },
 :group_method => :last,
 :label_method => :upcase,
 :value_method => :downcase %>
like image 171
dolzenko Avatar answered Oct 30 '22 16:10

dolzenko


If you hava two models which are category, subcategory as follows:

class Category < ActiveRecord::Base
    has_many :products
    has_many :subcategories
end

class Subcategory < ActiveRecord::Base
    belongs_to :category
    has_many :products
end

Then you can use

<%= simple_form_for [:admin, @yourmodel] do |f| %>
    <%= f.input :subcategory_id, collection: Category.all, as: :grouped_select, group_method: :subcategories, prompt: "Select One" %>
    <%= f.submit "Submit" %>
<% end %>

which result like this:

<div class="form-group grouped_select optional yourmodel_subcategory_id">
    <label class="grouped_select optional control-label" for="yourmodel_subcategory_id">Subcategory</label>
    <select class="grouped_select optional form-control" id="yourmodel_subcategory_id" name="yourmodel[subcategory_id]">
    <option value="">Select One</option>
    <optgroup label="Your 1st Category">
        <option value="This subcategory id">one subcategory belongs to Your 1st Category</option>
    </optgroup>
    <optgroup label="Your 2nd Category">
        <option value="This subcategory id">one subcategory belongs to Your 2nd Category</option>
    </optgroup>
    </select>
</div>

Hope this helps.

like image 22
hungming Avatar answered Oct 30 '22 17:10

hungming