I am trying to generate the Form Select with the OPTGROUP tags, from a
simple array. For example I have an array : [Acer, laptop, 1], [Acer,
monitor, 2], [HP, desktop, 3], [HP, printer,4]
I know how to use the Select helper to generate the Select - Option
tags from an array. But I just couldn't figure out how to do with the
OPTGROUP tag.
I would like to produce the final result from the array as:
<optgroup label="Acer">
<option value="1">laptop</option>
<option value="2">monitor</option>
...
</optgroup>
<optgroup label="HP">
<option value="3" >Desktop</option>
<option value="4">Printer</option>
...
</optgroup>
I know there is a helper called
option_groups_from_collection_for_select. But from what I understand
this helper is only based on the object relationships of its
arguments. I would like to generate from a simple array, using a
helper.
I have spend hours trying to figure this out but without success. Any
help will be greatly appreciated.
Thanks in advance.
Steve
I am trying to generate the Form Select with the OPTGROUP tags, from a
simple array. For example I have an array : [Acer, laptop, 1], [Acer,
monitor, 2], [HP, desktop, 3], [HP, printer,4]
I know how to use the Select helper to generate the Select - Option
tags from an array. But I just couldn't figure out how to do with the
OPTGROUP tag.
You've just got completely the wrong data structure. Either coerce
your data into the form expected by
option_groups_from_collection_for_select (eg use some structs; you may
find group_by helpful) or just do it all by hand
Fred
Fred, thanks for your input. Having spending sometime understanding
option_groups_from_collection_for_select, I agreed with you that my
data structure above was all wrong.
Let me try again to describe my problem after approaching the problem
differently.
I am trying to have a Select dropdown by groups whereby the content of
this dropdown would be the names that come from a data table called
User with the following attribs.
class User < ActiveRecord::Base
# attribs: id, name, location
end
I have tried using the option_groups_from_collection_for_select as
follows:
option_groups_from_collection_for_select(User.find(:all),
User.find(:all, :order => 'location DESC,
name'), :location, :name, :name)
hoping to get something like the following result:
<optgroup label="CA">
<option value="Henry">Henry</option>
<option value="James">James</option>
...
</optgroup>
<optgroup label="TX">
<option value="Gordon">Gordon</option>
<option value="Sally">Sally</option>
<option value="Thomas">Thomas</option>
...
</optgroup>
This doesn't seem to be correct. If someone could help point out what
I am not doing right, that would be most appreciated.
Thanks in advance.