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.
What I ended up doing is to just create a normal text input and prepopulate it with an ISO formatted date and additional information to mark it as a date input (say, rel="date").
On the client side, I have JavaScript to create a new hidden input that takes on the name of the original field (thus overriding it, for good measure I also delete the name property of the original). The datepicker is attached to the original field, and uses altField/altFormat to sync the hidden field with an ISO date.
This appears to keep everything in sync, sends the proper date format to the application, and degrades as well as anyone would expect it to.
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 -
More examples @ Rails date format in a text_field
if your are using mysql database you can format the date in query itself.
Sample code
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 theshow
object from the parent view. I changed therender
line to include it - the parent view now looks like this: