When I use the helper
= f.date_select :date_of_birth
it will generate 3 select boxes next to each other:
<select id="user_date_of_birth_3i" name="user[date_of_birth(3i)]">...</select>
<select id="user_date_of_birth_3i" name="user[date_of_birth(2i)]">...</select>
<select id="user_date_of_birth_3i" name="user[date_of_birth(1i)]">...</select>
So one Rails helper will create these 3 select boxes. I would need to put there a Rails helper, that would generate only one select box, like:
= f.date_select :date_of_birth_3i
(but this generate an error)
would generate
<select id="user_date_of_birth_3i"> name="user[date_of_birth(3i)]">...</select>
and the same for the two other select boxes...
Is there any way to achieve that?
Thank you
I just came up with a solution based on the form tag helper select_year and friends:
<%=
select_year(
my_object.date_field.try(:year),
{
:prompt => "",
:start_year => Time.zone.now.year,
:end_year => Time.zone.now.year + 4,
:field_name => :"date_field(1i)",
:prefix => :my_object
},
:class => "form-control"
)
%>
This is kind of ugly because it not taking any information from the surrounding form and we have to set up the selected value, the special field_name with the (1i) and such.
So I ended up with a helper:
module DateSelectHelper
def date_select_year(object, field_name, opts = {}, html_opts = {})
merged_opts = {
:prompt => "",
:start_year => Time.zone.now.year,
:end_year => Time.zone.now.year + 4,
:field_name => :"#{field_name}(1i)",
:prefix => object.class.name.underscore
}.merge(opts)
select_year(object.send(field_name).try(:year), merged_opts, html_opts)
end
def date_select_month(object, field_name, opts = {}, html_opts = {})
merged_opts = {
:prompt => "",
:field_name => :"#{field_name}(2i)",
:prefix => object.class.name.underscore
}.merge(opts)
select_month(object.send(field_name).try(:month), merged_opts, html_opts)
end
def date_select_day(object, field_name, opts = {}, html_opts = {})
merged_opts = {
:prompt => "",
:field_name => :"#{field_name}(3i)",
:prefix => object.class.name.underscore
}.merge(opts)
select_day(object.send(field_name).try(:day), merged_opts, html_opts)
end
end
And you can use it like this:
<div class="col-sm-2">
<%= date_select_year(f.object, :date_field, { :start_year => Time.zone.now.year, :end_year => Time.zone.now.year + 4 }, { :class => "form-control" }) %>
</div>
<div class="col-sm-3">
<%= date_select_month(f.object, :date_field, {}, { :class => "form-control" }) %>
</div>
<div class="col-sm-2">
<%= date_select_day(f.object, :date_field, {}, { :class => "form-control" }) %>
</div>
I'm still testing it .. but it looks like it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With