I'm a beginner to ruby and ruby on rails, and I'm attempting to create a complex form using simple_form. Everything is working already, but I wanted to customize the "time" field in a very specific way.
When I use:
<%= f.input :hour %>
It renders two select fields, being the "hour" field populated with options from 00 to 23, and the "minute" field populated with options from 00 to 59.
But that's not what I want. I want to replace the use of two select fields for the time with a single select field with custom pre-populated options, with time ranging from 8am until 22pm, in 15 minutes increments, and also have the text for the options show times with the syntax "8h00", "8h15", "8h30", "8h45", "9h00", "18h00", "18h15", "18h30", "18h45", etc.. being "21h45" the last option available.
I have managed to customize it a bit more using these options:
<%= f.input :hour, :as => :time, :minute_step => 15 %>
Although that solves the 15 minute increment problem, it still renders two select fields.
This would be the html equivalent of what I wanted to have simple_form render for me:
<select name="hour">
<option value="08:00:00">08h00</option>
<option value="08:15:00">08h15</option>
<option value="08:30:00">08h30</option>
<option value="08:45:00">08h45</option>
...
<option value="21:30:00">21h30</option>
<option value="21:45:00">21h45</option>
</select>
I'm pretty sure this is very easy to implement using a collection that loops from 8..21 and then loops again with '00', '15', '30' and '45', and then outputs options in the syntax that I want (hour + "h" + minute).
I want to create a custom "date" field, because there will many date fields in a single form (for a "appointment" related application that I'm creating), but since I'm a beginner on ruby on rails, I'm really lost on what would be the most smart way to implement this. I'm not sure if I should implement a custom field in simple_form, if I should use a helper function, or what.
With help from Carlos Antonio da Silva, from simpleform's mailing list, we've fixed this by creating a custom input like this:
class HourInput < SimpleForm::Inputs::Base
def input
@builder.select(attribute_name, hour_options, { :selected => selected_value }, { :class => "input-medium" })
end
private
# The "Selecione..." string could also be translated with something like: I18n.t("helpers.select.prompt')
def hour_options
hour = [['Selecione...', '00:00:00']]
(8..21).each do |h|
%w(00 15 30 45).each do |m|
hour.push ["#{h}h#{m}", "#{"%02d" % h}:#{m}:00"]
end
end
hour
end
def selected_value
value = object.send(attribute_name)
value && value.strftime("%H:%M:%S")
end
end
and then <%= f.input :hora, :as => :hour %>
in the view.
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