Formatting a date input using simple_form

不问归期 提交于 2019-11-30 23:40:19

问题


I have a date type field in my database.

Here's the view code I'm using:

# Using 'as: :string' to avoid those three dropdowns rails generates.
= f.input_field :start_date, as: :string, class: 'form-control datepicker'

When saving a date I use a jquery plugin that shows a calendar and writes in a date like: 11/05/2013.

But when editing the same record, the input is populated with a value 2013-05-11.

How can I make it so simple_form actually respects my date format defined in en.yml?


回答1:


Here's what you need :

f.input :my_date,
        :as => :string, 
        :input_html => { :value => localize(f.object.my_date) }

PS : This was the first link in google search :)




回答2:


I created this class which makes it easy to do this:

f.input :my_date, :as => :date_picker

Add this class to your lib/ folder and be sure to include it (or configure it to autoload):

class DatePickerInput < SimpleForm::Inputs::StringInput
  def input
    value = @builder.object.send(attribute_name)
    input_html_options[:value] = case value
                                   when Date, Time, DateTime
                                     format = options[:format] || :medium
                                     value.to_s(format)
                                   else
                                     value.to_s
                                 end

    input_html_options[:class] ||= []
    input_html_options[:class] << "date_picker_input"
    @builder.text_field(attribute_name, input_html_options)
  end
end


来源:https://stackoverflow.com/questions/19761080/formatting-a-date-input-using-simple-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!