簡體   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