Tintin81
Tintin81

Reputation: 10207

How to create a Datepicker FormHelper in Rails?

In my Rails 4 application I have this helper method that creates a text_field with a hidden_field just underneath it:

module FormatHelper

  def datepicker_field(f, options = {})
    text_field_tag(nil, format_date(f.object.date || Date.today), options) +
    f.hidden_field(:date)
  end

end

In my forms I use it like this:

<%= datepicker_field(f) %>

I would prefer to do this instead, though:

<%= f.datepicker_field(:date) %>

How can this be done in Rails?

Thanks for any help.

Upvotes: 0

Views: 48

Answers (1)

Fer
Fer

Reputation: 3347

You can build your own Formbuilder class and use it in a particular form:

Taken from the Formbuilder docs :

class MyFormBuilder < ActionView::Helpers::FormBuilder
  def div_radio_button(method, tag_value, options = {})
    @template.content_tag(:div,
      @template.radio_button(
        @object_name, method, tag_value, objectify_options(options)
      )
    )
  end
end

and then your form should be something like:

<%= form_for @person, :builder => MyFormBuilder do |f| %>
  I am a child: <%= f.div_radio_button(:admin, "child") %>
  I am an adult: <%= f.div_radio_button(:admin, "adult") %>
<% end -%>

Upvotes: 1

Related Questions