instance method
grouped_options_for_select
Ruby on Rails 3.0.20
Since v2.3.18Signature
grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil)
Returns a string of <option> tags, like options_for_select, but wraps them with <optgroup> tags.
Parameters:
-
grouped_options- Accepts a nested array or hash of strings. The first value serves as the<optgroup>label while the second value must be an array of options. The second value can be a nested array of text-value pairs. Seeoptions_for_selectfor more info.Ex. ["North America",[["United States","US"],["Canada","CA"]]]
-
selected_key- A value equal to thevalueattribute for one of the<option>tags, which will have theselectedattribute set. Note: It is possible for this value to match multiple options as you might have the same option in multiple groups. Each will then getselected="selected". -
prompt- set to true or a prompt string. When the select element doesn’t have a value yet, this prepends an option with a generic prompt - “Please select” - or the given prompt string.
Sample usage (Array):
grouped_options = [ ['North America', [['United States','US'],'Canada']], ['Europe', ['Denmark','Germany','France']] ] grouped_options_for_select(grouped_options)
Sample usage (Hash):
grouped_options = {
'North America' => [['United States','US], 'Canada'],
'Europe' => ['Denmark','Germany','France']
}
grouped_options_for_select(grouped_options)
Possible output:
<optgroup label="Europe"> <option value="Denmark">Denmark</option> <option value="Germany">Germany</option> <option value="France">France</option> </optgroup> <optgroup label="North America"> <option value="US">United States</option> <option value="Canada">Canada</option> </optgroup>
Note: Only the <optgroup> and <option> tags are returned, so you still have to wrap the output in an appropriate <select> tag.
Parameters
-
grouped_optionsreq -
selected_keyopt = nil -
promptopt = nil
Source
# File actionpack/lib/action_view/helpers/form_options_helper.rb, line 449
def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil)
body = ''
body << content_tag(:option, prompt, { :value => "" }, true) if prompt
grouped_options = grouped_options.sort if grouped_options.is_a?(Hash)
grouped_options.each do |group|
body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0])
end
body.html_safe
end
Defined in actionpack/lib/action_view/helpers/form_options_helper.rb line 449
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::FormOptionsHelper