views:

1030

answers:

3

I need to produce a select menu with a Default value on the list of <options> . Here is how I need it looks like.

<select name="menu[parent_id]" id="menu_parent_id">
 <option value="0">==None==</option>
 <option value="34">TEST</option>
</select>

Currently I use this select helper in my form

   <%= f.select(:parent_id, @parent_menus.collect {|p| [ p.name, p.id ] }, {:include_blank => '==None=='})%>

the above code produce this; (value="")

<select name="menu[parent_id]" id="menu_parent_id">
 <option value="">==None==</option>
 <option value="34">TEST</option>
</select>

Does anyone here can show me a way to add value="0" to the options list?

+3  A: 
<%= f.select(:parent_id, [["==None==", 0]] + @parent_menus.collect {|p| [ p.name, p.id ] }) %>
Simone Carletti
Here is what I get for that,`<option value="==None==">==None==</option><option selected="selected" value="0">0</option>`Actually I'm looking for something like this`<option value="0">==None==</option>`
randika
Sorry, my fault. I forgot one []. Check out my update.
Simone Carletti
Hooray it worked! thanks a bunch Simone. I'll make this as the answer.
randika
A: 

Try

<%= f.select(:parent_id, options_for_select(["==None==", 0] + @parent_menus.collect {|p| [ p.name, p.id ] }, 0)) %>
Max Williams
Sorry this is not what I need. It gives me ==None== as the display name but the value attribute also value="==None==".`<select name="menu[parent_id]" id="menu_parent_id">``<option value="==None==">==None==</option>``<option selected="selected" value="0">0</option>``<option value="45">TEST 1</option>``<option value="46">TEST 2</option>``</select>`I need to set 0 for the default display option value.`<select name="menu[parent_id]" id="menu_parent_id">``<option value="0">==None==</option>``<option value="45">TEST 1</option>``<option value="46">TEST 2</option>``</select>`
randika
A: 

I don't know this is Ruby way or not But this will definietly work

<%= f.select(:parent_id, "<option value='0'>Please select</option>"+options_for_select(@parent_menus.collect {|p| [ p.name, p.id ] }))%>

EDITED. For pre-selected according to the value save in database i assume @user is your object contain the database value for following example.

<%= f.select(:parent_id, "<option value='0'>Please select</option>"+options_for_select(@parent_menus.collect {|p| [ p.name, p.id ] }, @user.id ))%>
Salil
Yeah this is definitely not rails way. I too use use something similar here. this works for inserting records perfectly. But the problem comes when we need need to edit/update the records, because the select menu doesn't set the `selected="selected"` attribute to the relevant option menu. its always the top one.here is my current code: `<select name="menu[parent_id]">` `<option value="0"> ==None== </option>` `<% @parent_menus.each do |parent| -%>` `<option value="<%= parent.id -%>"> <%= parent.name -%>` `</option>` `<% end %>` </select>`
randika
please check my Edited Answer hope that helps.
Salil