Struggling with Date fields - select_month and select_year

If that's your exact code, then you haven't provided for any way to mark which item has been selected.

Just like you have to populate the value="" attribute in <input> tags, you have to populate the selected="selected" attribute of the <select> tag.

Here's the tedous way to do that, which whos you the prinicple. It assumes your form data is in

<select id="magazine_start_date_month" name="magazine[start_date_month]">

<option value=""></option>

<option value="1"<%= if magazine.start_date_month == '1'; ' selected="selected"'; end %>>January</option>

<option value="2"<%= if magazine.start_date_month == '2'; ' selected="selected"'; end %>>February</option>

<option value="3"<%= if magazine.start_date_month == '3'; ' selected="selected"'; end %>>March</option> ... </select>

Of course doing that manually for all select tags in your app can be tedious and prone to errors, so writing a generic routine to draw these things is usually a good idea. I have a general purpose library for defining, caching, and drawing value lists like this.

-- greg willits

Thanks Greg. I managed to write a helper function to return the option tag with selected = "selected" set.

Helper Function: def build_selected_option_for_months(value)     months = Date::MONTHNAMES     return '<option value="' + value.to_s + '"selected="selected">' + months[value] + '</option>' end In the view:

option value=""></option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> <%= build_selected_option_for_months(@user_company.start_date_month) %> </select> Thanks a lot again.

Regards, Sandeep G

Sandeep Gudibanda wrote: