How do i write a cleaner date picker input for SimpleForm

后端 未结 5 1754
萌比男神i
萌比男神i 2020-12-04 07:23

I love the simple_form gem for rails but i dont like this line of code:

<%= f.input :deadline, :as => :string, :input_html => { :class          


        
5条回答
  •  没有蜡笔的小新
    2020-12-04 08:03

    The answers here seem a bit out of date if you are using simple_form 2.0.

    I've been fighting with this for a while and was able to concoct this; it uses inheritance (notice that it is a subclass of StringInput, not Base), supports i18n and adds the datepicker css class in a more clean way, IMHO.

    # app/inputs/date_picker_input.rb
    
    class DatePickerInput < SimpleForm::Inputs::StringInput 
      def input                    
        value = input_html_options[:value]
        value ||= object.send(attribute_name) if object.respond_to? attribute_name
        input_html_options[:value] ||= I18n.localize(value) if value.present?
        input_html_classes << "datepicker"
    
        super # leave StringInput do the real rendering
      end
    end
    

    The usage is like above:

    <%= f.input :deadline, :as => :date_picker %>
    

    And the javascript remains the same:

    $("input.date_picker").datepicker();
    

提交回复
热议问题