Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

ruby on rails - How do i write a cleaner date picker input for SimpleForm

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' } %>

I would like to write:

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

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

But i dont really want to write a whole custom_simple_form

I think it must be possible...

Please help thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...