Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select tag, specifying the selected option (or moving an array element to index 0)

Say I'm querying a list of fruit and then collecting just the id's and name's of the fruit into @fruit.

[32, "apple"],
[8, "bannana"],
[10, "cantelope"],
[11, "grape"],
[15, "orange"],
[41, "peach"],
[22, "watermelon"]

@fruit is being used in a Select helper. "apple" being at index 0 of @fruit will be the selected value (first option) of the select. This is a made up example but by default I'll always know what "orange" is by name (not by id). I need "orange" to be the selected value of the select tag (the first option).

":prompt => 'orange'" just adds a 2nd instance of "orange" in the select. Everything I've found on Google so far seems to be about adding an extra value or blank to the list.

Since index 0 of the array always becomes the selected value (if no prompt or blank is used in the select helper), is there a way I could find the index containing the name "orange" (@fruit[x].name == 'orange'), and move it to index 0 while retaining the existing alpha sort in the rest of the list? So, the @fruit array would look like:

@fruit[0]    [15, "orange"],
@fruit[1]    [32, "apple"],
@fruit[2]    [8, "bannana"],
@fruit[3]    [10, "cantelope"],
@fruit[4]    [11, "grape"],
@fruit[5]    [41, "peach"],
@fruit[6]    [22, "watermelon"]

The only thing I can think of right now would be to iterate through @fruit and if "orange" is found add it to a new array. Then iterate through the @fruit array again and add anything that doesn't have a name of "orange". I'm not sure how to write that out but it seems like it would do what I'm looking for. Maybe there's some easy way to do this I'm missing (specifying which index in an Array is to be the first option written)?

Thank You!

like image 793
Reno Avatar asked Jan 31 '11 05:01

Reno


2 Answers

See here: http://guides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease

If you use the existing helpers, you can specify by id which option you want selected. Specifically this example:

<%= options_for_select([['Lisbon', 1], ['Madrid', 2]], 2) %>

output:

<option value="1">Lisbon</option>
<option value="2" selected="selected">Madrid</option>

You say you don't know which option is "orange" by ID. If you want to find the ID for "orange" in the fruit array this would do it, then you can use the helper:

(@fruit.detect { |i| i[1] == 'orange' } || []).first
like image 175
ctcherry Avatar answered Oct 10 '22 01:10

ctcherry


You can use options_from_collection_for_select in the select tag for selecting a default option. For example:

<%= select_tag 'state',
    options_from_collection_for_select(@fruits, 'id', 'name', 15),
    :include_blank => true %>

This would select 'Orange' by default. API Docs.

like image 37
Syed Aslam Avatar answered Oct 10 '22 03:10

Syed Aslam