views:

450

answers:

3

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

+1  A: 

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.)

Ryan McGeary
A: 

Thank you very much Ryan. Your first solution worked great in the show and index views, but had no impact on the form input text field. Still, I never made an initializer before, so that is useful information. The second solution - I must be botching it, because it throws a "no method error." undefined method `object' for nil:NilClass

I used this syntax based on your example:

<p>
  <%= f.label :start %><br />
  <%- start_string = form.object.start && form.object.start.strftime("%A, %b %e, %G - %I:%M %p") -%>
  <%= f.text_field :start, :class => 'jqueryCDS', :value => start_string %>
</p>

(The "jqueryCDS" class is what triggers the calendar select widget, and shouldn't have any bearing on the date formatting.) Maybe you intended "object" to be replaced with something else. I tried "text_field" and "input" without success.

Thanks again Ryan. I remain stumped. Steve

A: 

Got it, but had to use a conventional HTML input element, not the Rails helper:

<input type="text" id="assignment_starts_at" name="assignment[starts_at]" class="jqueryCDS" size="30" value="<%= @assignment.starts_at.strftime('%A, %b %e, %G - %I:%M %p') if @assignment.starts_at %>" />