简体   繁体   中英

How to get default value for Formtastic date / time select?

I am using Formtastic 1.2.3. I want the current date and time already to be selected when the form is loaded. I tried many combinations with :default or :selected , but none worked. Even from the github page of Formtastic I can't get information on that. Any suggestions? Thanks for your time!

= form.input :date,:hint => 'Select a date',
             :prompt => {:day => "Day", :month => "Month", :year => "Year"},
             :start_year => Time.now.year
= form.input :time

Using after_initialize to set a default value for a form is too heavy-handed. What about cases when blank values are acceptable? This is the responsibility of the controller, not the model.

class ResourceController < ApplicationController
  def new
    # do stuff
    @resource.important_date ||= Time.zone.today
  end
end 

I've done this by setting the value in the active record object directly when it's created like so:

In the model class:

def after_initialize
  self.start_time ||= Time.now
end

Then when the form is displayed, it will already have the time populated and set correctly.

I agree with @Jeriko. Using an after_initialize just begs for trouble. Another option if you do not have access to the controller (or don't want to access it) is to do something like this:

(f.object.received_on = Time.zone.today) unless f.object.received_on.present?

I needed to do this to initialize an Active Admin form where I don't want to access the controller and definitely don't want to touch the model.

Your syntax looks alright and it should work (works for me). You might want to add the :as => :date constraint as well just in case.

form.input :date, :as => :date, :hint => 'Select a date',
         :prompt => {:day => "Day", :month => "Month", :year => "Year"},
         :start_year => Time.now.year

I found this discussion on Google Groups, where Justin French discusses the same. Maybe that will also help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM