本文介绍了我如何为 SimpleForm 编写更清晰的日期选择器输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢 Rails 的 simple_form gem,但我不喜欢这行代码:

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

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

我想写:

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

甚至完全覆盖 :date/:datetime 匹配器.

or even over write the :date / :datetime matchers completely.

但我真的不想写一个完整的custom_simple_form

But i dont really want to write a whole custom_simple_form

我认为这一定是可能的...

I think it must be possible...

请帮忙谢谢

推荐答案

你必须定义一个新的 DatePickerInput 类.

You have to define a new DatePickerInput class.

module SimpleForm
  module Inputs
    class DatePickerInput < Base
      def input
        @builder.text_field(attribute_name,input_html_options)
      end    
    end
  end
end

你现在可以写

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

当然你也需要

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

application.js

这对于本地化日期非常有用.看看这个:

This is very useful to localize dates. Look at this:

module SimpleForm
  module Inputs
    class DatePickerInput < Base
      def input
        @builder.text_field(attribute_name, input_html_options.merge(datepicker_options(object.send(attribute_name))))
      end

      def datepicker_options(value = nil)
        datepicker_options = {:value => value.nil?? nil : I18n.localize(value)}
      end

    end
  end
end

您现在在文本字段中有一个本地化的日期!

You have now a localized date in the text field!

更新:一种更简洁的方法

module SimpleForm
  module Inputs
    class DatePickerInput < SimpleForm::Inputs::StringInput
      def input_html_options
        value = object.send(attribute_name)
        options = {
          value: value.nil?? nil : I18n.localize(value),
          data: { behaviour: 'datepicker' }  # for example
        }
        # add all html option you need...
        super.merge options
      end
    end
  end
end

SimpleForm::Inputs::StringInput 继承(如@kikito 所说)并添加一些 html 选项.如果你还需要一个特定的类,你可以添加类似

Inherit from SimpleForm::Inputs::StringInput (as @kikito said) and add some html options.If you need also a specific class you can add something like

def input_html_classes
  super.push('date_picker')
end

这篇关于我如何为 SimpleForm 编写更清晰的日期选择器输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 20:39