Reputation: 4391
I have a few forms in my application which where using date_select
and I've just changed to using date_field
(which uses the HTML5 form elements) the only issue I'm having is that date_select
would default to todays date which was perfect for us but date_field
is defaulting to dd/mm/yyyy
instead.
I'm running into issues with people blindly submitting the form and triggering validation errors.
Is it possible to default date_field
to today?
Upvotes: 22
Views: 21478
Reputation: 326
None of these options worked for me, trying to use a date_field_tag
.
What did work is passing the value like this:
date_field_tag(:my_thing_end_date, :end_date, value: Date.current.strftime('%Y-%m-%d')
From the docs ( http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormHelper/date_field)
The default value is generated by trying to call “to_date” on the object’s value, which makes it behave as expected for instances of DateTime and ActiveSupport::TimeWithZone.
So passing the date as a string that would be entered by the user seems to be the solution.
Also, according to this good info on dates and time zones, Date.current
is preferable to Time.today
: https://robots.thoughtbot.com/its-about-time-zones.
Upvotes: 2
Reputation: 378
Setting the :value, as many of these answers suggest, will overwrite a value that is passed in for any record being edited. This is not a problem if the form is only for new entries, but buggy if you want to edit records in the form. One way around this is to grab the existing object explicitly, as Michael suggests.
The solution I'm currently using is in the Controller, which sets the value to today when it builds the new record. Assuming your model is Person, and the value you want to default is start_date:
def new
@person = Person.new(start_date: Date.current)
end
You can then just use the value in the form without any additional fuss.
f.date_field :start_date
Upvotes: 6
Reputation: 19
In Rails for you can also do following: ' <%= f.date_field :birthday, :value => Date.today %>
Upvotes: 0
Reputation: 7374
Using Time object for a date field didn't work for me, I had to use the Date object.
Resulting view code for Rails 4:
<%= f.date_field :birthday, placeholder: "YYYY-MM-DD", value: (f.object.birthday || Date.today.to_s(:db)) %>
Upvotes: 0
Reputation: 316
If you installed Rails4 via gem, it has below bug yet.
Fix above and you can set default value like this
<%= f.date_field :birthday, :value => Time.now.strftime('%Y-%m-%d') %>
Upvotes: 30
Reputation: 6438
This will run correctly :
<%= f.date_field :birthday, :value => Time.now.strftime("%Y-%m-%d") %>
Upvotes: 2
Reputation: 5111
You can set the default date_field like this
date_field("user", "born_on", value: Time.now.to_s(:db))
Upvotes: 2