2011-12-20 27 views
2

我在窗體上使用simple_form gem,並且想要使用具有三個text_fields字段而不是三個選擇字段的日期字段。將simple_form日期輸入更改爲具有三個字符串輸入而不是三個下拉菜單

我嘗試這樣做:

<%= profile_form.simple_fields_for :birthday do |date| %> 
    <%= date.input :day, :as => :string, :label => "Dia", :input_html => { :maxlength => 2 } %> 
    <%= date.input :month, :as => :string, :label => "Mês", :input_html => { :maxlength => 2 } %> 
    <%= date.input :year, :as => :string, :label => "Ano", :input_html => { :maxlength => 4 } %> 
<%- end -%> 

但是,創建三個div的,三個標籤,這是一個爛攤子。 理想的情況是一行一個標籤和三個字符串字段。

任何想法如何創建自定義輸入?

回答

2

隨着郵件列表的幫助simple_form我終於明白了。 自定義輸入如下:

class CustomDateInput < SimpleForm::Inputs::Base 
    def input 
    "#{@builder.text_field("day", input_html_options)}".html_safe + 
    "#{@builder.text_field("month", input_html_options)}".html_safe + 
    "#{@builder.text_field("year", input_html_options)}".html_safe 
    end 

    #Makes the label target the day input 
    def label_target 
    "day" 
    end 
end 

日,月和年是需要被創建的虛擬屬性。 我已經將它們添加到模塊中,以便它們可以在我的模型中混合使用。 模塊看起來是這樣的:

module Extensions 
    module DateFields 

    attr_accessor :day, :month, :year 

    def fulldate 
     Date.parse("#{@day}-#{@month}-#{@year}") 
    end 
    end 
end 

現在,在我的模型可以這樣做:

class Profile < ActiveRecord::Base 
    belongs_to :user 
    before_save :update_birthday 

    include Extensions::DateFields 

    private 
    def update_birthday 
    unless fulldate == true || nil? 
     self.birthday=fulldate 
    end 
    end 

end 
1

如果您搜索的自定義輸入上SimpleForm's readme我相信你可以寫出像這樣的自定義輸入..

# app/inputs/inline_input.rb 
class InlineInput < SimpleForm::Inputs::Base 
    def input 
    "<span>#{@builder.text_field(attribute_name, input_html_options)}</span>".html_safe 
    end 
end 

然後調用它像這樣

<%=profile_form.simple_fields_for :birthday do |date| %> 
    <%= date.input :day, :as => :inline, :label => false, :input_html => { :maxlength => 2 } %> 
    <%= date.input :month, :as => :inline, :label => false, :input_html => { :maxlength => 2 } %> 
    <%= date.input :year, :as => :inline, :label => false, :input_html => { :maxlength => 4 } %> 
<%- end -%> 
+0

謝謝麥克。我已經嘗試過,但每個輸入仍然呈現在DIV內部。我猜我應該嘗試使用CSS對3個DIV進行分組?但是,如果DateTime Input帶有三個下拉列表,它應該可以將它們更改爲三個跨度......我無法弄清楚:/ – 2012-01-11 22:11:52

相關問題