Formtastic is a great little gem
for cleaning up form code in your Rails view. It provides a neat DSL for
building forms and outputs semantic markup with plenty of hooks for you to
style with.
The project readme has extensive samples, but here’s what a simple form might
look like:
Formtastic is smart enough to detect your attribute types and renders an
appropriate form element. If you don’t like what it chooses, overriding the
element type is as easy as an extra option to the input method.
One limitation is that it only supports the standard form elements available in
the rails API. What if you want something different - like some fancy image
based thing? or a non-standard date picker? or some new-fandangled HTML5 input
type?
The readme has a tantalising hint on custom inputs, but doesn’t go into much
detail
Imagine your model has a date attribute that always stores a Monday. You want
users to pick a date by selecting from a list of options formatted with
commercial weeks (week 22 2010, week 23 2010, etc).
Start by creating lib/my_custom_builder.rb. Create a class that extends the default
formtastic builder and add your own input type. The default builder has a heap
of helper methods you can use, so have that open at the same time.
Then edit your formtastic settings in config/initializers/formtastic.rb and tell it
to use your new builder instead of the default
Restart your app, and then use the new input type in a form