Skip to content

Instantly share code, notes, and snippets.

@jesperronn
Created September 1, 2009 12:34
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jesperronn/179075 to your computer and use it in GitHub Desktop.
grouped_select for Rails 2.3 to simplify using optgroups
<li class="expense_item">
<%= expense.grouped_select :expense_type_id, ExpenseType.groups, {:include_blank => true}, {:class => 'expense_type'} %>
...
</li>
require 'form_options_helper'
class ExpenseType < ActiveRecord::Base
validates_uniqueness_of :name
#returns grouped options split in 'popular' and 'all'
def self.groups
all_types = self.all.map{|t| [t.name, t.id]}
[
['popular', all_types[0..2]],
['all', all_types]
]
end
end
require 'action_view/helpers/form_helper'
module ActionView
module Helpers
module FormOptionsHelper
##
def grouped_select(object, method, choices, options = {}, html_options = {})
InstanceTag.new(object, method, self, options.delete(:object)).to_grouped_select_tag(choices, options, html_options)
end
end
class InstanceTag
include FormOptionsHelper
def to_grouped_select_tag(choices, options, html_options)
html_options = html_options.stringify_keys
add_default_name_and_id(html_options)
value = value(object)
selected_value = options.has_key?(:selected) ? options[:selected] : value
disabled_value = options.has_key?(:disabled) ? options[:disabled] : nil
content_tag("select", add_options(grouped_options_for_select(choices, :selected => selected_value, :disabled => disabled_value), options, selected_value), html_options)
end
end
class FormBuilder
def grouped_select(method, choices, options = {}, html_options = {})
@template.grouped_select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options))
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment