【问题标题】:Changing simple_form date input to have three string inputs instead of three drop down menus将 simple_form 日期输入更改为具有三个字符串输入而不是三个下拉菜单
【发布时间】:2011-12-20 17:43:06
【问题描述】:

我在表单上使用 simple_form gem,并希望使用具有三个 text_fields 字段而不是三个选择字段的日期字段。

我试过了:

<%= 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 和三个标签,而且一团糟。 理想的情况是一行中有一个标签和三个字符串字段。

有什么想法可以创建自定义输入吗?

【问题讨论】:

    标签: datepicker simple-form


    【解决方案1】:

    在 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
    

    【讨论】:

      【解决方案2】:

      如果您在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 -%>
      

      【讨论】:

      • 谢谢你,迈克。我已经尝试过了,但是每个输入仍然会在 DIV 中呈现。我猜我应该尝试使用 CSS 对 3 个 DIV 进行分组?但是,如果 DateTime 输入带有三个下拉菜单,则应该可以将它们更改为三个跨度...我只是想不通:/
      猜你喜欢
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 2011-10-29
      • 2013-06-09
      相关资源
      最近更新 更多