2013-11-04 140 views
8

我在我的數據庫中有一個date類型字段。使用simple_form格式化日期輸入

下面是我使用的視圖代碼:

# 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中定義的日期格式?

回答

29

這裏有您需要什麼:

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

PS:這是在谷歌search第一個鏈接:)

+3

什麼搜索條件 – callum

+3

值得一提的是,您可以指定本地化函數的格式,例如'localize(f.object.my_date,format::short)' – jmarceli

+0

您還可以提供如下格式:'localize(f.object.my_date,format:「%-m /%d /%Y」)' – dinjas

9

我創造了這個類可以很容易地做到這一點:

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

將此類添加到您的庫文件夾中,並確保將其包含(或將其配置爲自動加載):

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