Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format text_field helper?

Is it possible to apply strftime formatting to the value of a text input field using a Rails text_field helper? In the form I use for creating or editing a record, I have a text input field which is populated by a variant of the calendardateselect javascript. I click the text field and a little calendar pops up. After I select year, month, day and time the calendar goes away and what is left in the text input is a text representation of the date. That's what I see if I go to edit the record as well.

I'd like to modify how that date is displayed in the text input field. In other templates where that date is displayed I can use strftime, but I don't know how (or even if it's possible) to format the value of a text input field.

Thanks.

Steve

like image 738
user209835 Avatar asked Mar 05 '26 07:03

user209835


1 Answers

Option 1: If you have a default time format for your application, text_field will use that. For example, you might have a config/initializers/time_formats.rb containing the following:

Time::DATE_FORMATS[:default] = '%m/%d/%Y %I:%M %p'

Option 2: You can override the text_field's value using strftime directly. For example:

<%- scheduled_at_string = form.object.scheduled_at && form.object.scheduled_at.strftime("%m/%d/%Y") -%>
<%= form.text_field :scheduled_at, :value => scheduled_at_string %>

(You might want to clean this up with a helper.)

like image 140
Ryan McGeary Avatar answered Mar 06 '26 22:03

Ryan McGeary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!