繁体   English   中英

使用simple_form格式化日期输入

[英]Formatting a date input using simple_form

我的数据库中有一个date类型字段。

这是我正在使用的视图代码:

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

保存日期时,我使用一个显示日历的jquery插件,并在日期中写入: 11/05/2013

但是,在编辑同一记录时,输入将填充值2013-05-11

我怎样才能使它如此simple_form实际上尊重我在en.yml定义的日期格式?

这就是你需要的:

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

PS:这是谷歌搜索中的第一个链接:)

我创建了这个类,这样可以很容易地做到这一点:

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

将此类添加到lib /文件夹中并确保包含它(或将其配置为自动加载):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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