I have a form field in my Rails view like this:
<%= f.text_field :date, :class => "datepicker" %>
A javascript function converts all input fields of that class to a jQueryUI datepicker.
$(".datepicker").datepicker({
dateFormat : "dd MM yy",
buttonImageOnly : true,
buttonImage : "<%= asset_path('iconDatePicker.gif') %>",
showOn : "both",
changeMonth : true,
changeYear : true,
yearRange : "c-20:c+5"
})
So far so good. I can edit the record and it persists the date correctly all the way to the DB. My problem is when I want to edit the record again. When the form is pre-populated from the record it displays in 'yyyy-mm-dd' format. The javascript only formats dates which are selected in the datepicker control. Is there any way I can format the date retrieved from the database? At which stage can I do this?
Thanks, Dany.
Some more details following the discussion below, my form is spread across two files, a view and a partial. Here's the view:
<%= form_tag("/shows/update_individual", :method => "put") do %>
<% for show in @shows %>
<%= fields_for "shows[]", show do |f| %>
<%= render "fields", :f => f %>
<% end %>
<% end %>
<%= submit_tag "Submit"%>
<% end %>
And here's the _fields
partial view:
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.date %>
<%= f.label :date %>
<%= f.text_field :date, :class => "datepicker" %>
</p>
Controller code:
def edit_individual
@shows = Show.find(params[:show_ids])
end
I have added the following in environment.rb
:
Date::DATE_FORMATS.merge!(
:default => "%d %B %Y"
)
Now it's displaying the right format when I use @show.date in the view, but the form helper is still displaying the raw format.
JQuery datepicker won't format the pre-populated date.
You would need to handle it on the rails side by using the formatted date with the textfield, instead of the raw date which has the default 'yyyy-mm-dd' format.
Example -
<%= f.text_field :date, :class => "datepicker", :value => @model.date.strftime("%d %m %Y") %>
More examples @ Rails date format in a text_field
SOLVED: I pass in the :value => show.date
as suggested by Jayendra above. The reason it wasn't working was because I didn't pass in the show
object from the parent view. I changed the render
line to include it - the parent view now looks like this:
<%= form_tag("/shows/update_individual", :method => "put") do %>
<% for show in @shows %>
<%= fields_for "shows[]", show do |f| %>
<%= render "fields", :f => f, :show => show %>
<% end %>
<% end %>
<%= submit_tag "Submit"%>
<% end %>
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