README.textile

Formtastic

Formtastic is a Rails FormBuilder DSL (with some other goodies) to make it far easier to create beautiful, semantically rich, syntactically awesome, readily stylable and wonderfully accessible HTML forms in your Rails applications.

Compatibility

Formtastic 2.1.x is Rails 3.x compatible

Formtastic 2.0.x is Rails 3.0.x and 3.1.x compatible only

Formtastic 1.x is compatible with both Rails 2 and 3, and is being maintained for bug fixes in the the 1.2-stable branch. View the README in that branch for installation instructions, etc.

Formtastic, much like Rails, is very ActiveRecord-centric. Many are successfully using other ActiveModel-like ORMs and objects (DataMapper, MongoMapper, Mongoid, Authlogic, Devise…) but we’re not guaranteeing full compatibility at this stage. Patches are welcome!

The Story

One day, I finally had enough, so I opened up my text editor, and wrote a DSL for how I’d like to author forms:

I also wrote the accompanying HTML output I expected, favoring something very similar to the fieldsets, lists and other semantic elements Aaron Gustafson presented in Learning to Love Forms, hacking together enough Ruby to prove it could be done.

It’s awesome because…

It can handle belongs_to associations (like Post belongs_to :author), rendering a select or set of radio inputs with choices from the parent model.

It can handle has_many and has_and_belongs_to_many associations (like: Post has_many :tags), rendering a multi-select with choices from the child models.

It’s Rails 3 compatible (including nested forms).

It has internationalization (I18n)!

It’s really quick to get started with a basic form in place (4 lines), then go back to add in more detail if you need it.

There’s heaps of elements, id and class attributes for you to hook in your CSS and JS.

Stylesheet usage in Rails >= 3.1:

Rails 3.1 introduces an asset pipeline that allows plugins like Formtastic to serve their own Stylesheets, Javascripts, etc without having to run generators that copy them across to the host application. Formtastic makes three stylesheets available as an Engine, you just need to require them in your global stylesheets.

Conditional stylesheets need to be compiled separately to prevent them being bundled and included with other application styles. Remove require_tree . from application.css and specify required stylesheets individually.

If you have more than one form on the same page, it may lead to HTML invalidation because of the way HTML element id attributes are assigned. You can provide a namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generate HTML id. For example:

Customize HTML attributes for any input using the :input_html option. Typically this is used to disable the input, change the size of a text field, change the rows in a textarea, or even to add a special class to an input to attach special behavior like autogrow textareas:

Customize the HTML attributes for the <li> wrapper around every input with the :wrapper_html option hash. There’s one special key in the hash: (:class), which will actually append your string of classes to the existing classes provided by Formtastic (like "required string error").

Many inputs provide a collection of options to choose from (like :select, :radio, :check_boxes, :boolean). In many cases, Formtastic can find choices through the model associations, but if you want to use your own set of choices, the :collection option is what you want. You can pass in an Array of objects, an array of Strings, a Hash… Throw almost anything at it! Examples:

:country – a select menu of country names. Default for column types: :string with name "country" – requires a country_select plugin to be installed.

:email – a text field (just like string). Default for columns with name matching "email". New in HTML5. Works on some mobile browsers already.

:url – a text field (just like string). Default for columns with name matching "url". New in HTML5. Works on some mobile browsers already.

:phone – a text field (just like string). Default for columns with name matching "phone" or "fax". New in HTML5.

:search – a text field (just like string). Default for columns with name matching "search". New in HTML5. Works on Safari.

:hidden – a hidden field. Creates a hidden field (added for compatibility).

:range – a slider field.

The comments in the code are pretty good for each of these (what it does, what the output is, what the options are, etc.) so go check it out.

Delegation for label lookups

Formtastic decides which label to use in the following order:

1. :label # :label => "Choose Title"
2. Formtastic i18n # if either :label => true || i18n_lookups_by_default = true (see Internationalization)
3. Activerecord i18n # if localization file found for the given attribute
4. label_str_method # if nothing provided this defaults to :humanize but can be set to a custom method

Internationalization (I18n)

Basic Localization

Formtastic has some neat I18n-features. ActiveRecord object names and attributes are, by default, taken from calling @object.human_name and @object.human_attribute_name(attr) respectively. There are a few words specific to Formtastic that can be translated. See lib/locale/en.yml for more information.

Note: This is perfectly fine if you just want your labels/attributes and/or models to be translated using ActiveRecord I18n attribute translations, and you don’t use input hints and legends. But what if you do? And what if you don’t want same labels in all forms?

Enhanced Localization (Formtastic I18n API)

Formtastic supports localized labels, hints, legends, actions using the I18n API for more advanced usage. Your forms can now be DRYer and more flexible than ever, and still fully localized. This is how:

Note: Slightly different because Formtastic can’t guess how you group fields in a form. Legend text can be set with first (as in the sample below) specified value, or :name/:title options – depending on what flavor is preferred.

Creating New Inputs Based on Existing Ones

To create your own new types of inputs based on existing inputs, the process is similar. For example, to create FlexibleTextInput based on StringInput, put the following in app/inputs/flexible_text_input.rb:

Creating New Inputs From Scratch

To create a custom DatePickerInput from scratch, put the following in app/inputs/date_picker_input.rb:

class DatePickerInput
include Formtastic::Inputs::Base
def to_html
# ...
end
end

You can use your new input with :as => :date_picker.

Don’t subclass Formtastic::FormBuilder anymore

It was previously recommended in Formtastic 1.x to subclass Formtastic::FormBuilder to add your own inputs. This is no longer recommended in Formtastic 2, and will not work as expected.

Security

By default, Formtastic escapes HTML entities in both labels and hints unless a string is marked as html_safe. If you are using an older rails version which doesn’t know html_safe, or you want to globally turn this feature off, you can set the following in your initializer:

For significant changes, you may wish to discuss your idea on the Formtastic Google group before coding to ensure that your change is likely to be accepted. Formtastic relies heavily on i18n, so if you’re unsure of the impact this has on your changes, please discuss them with the group.