formtastic

Created: 2008-04-07 11:18
Updated: 2019-02-27 14:33
License: mit

README.md

Formtastic

Build Status Inline docs Code Climate Gem Version Dependency

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.

Documentation & Support

Compatibility

  • Formtastic 4 will require Rails 4.1 and Ruby 2.0 minimum
  • Formtastic 3 requires Rails 3.2.13 minimum
  • Formtastic 2 requires Rails 3
  • 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:

  <%= semantic_form_for @article do |f| %>

    <%= f.inputs :name => "Basic" do %>
      <%= f.input :title %>
      <%= f.input :body %>
      <%= f.input :section %>
      <%= f.input :publication_state, :as => :radio %>
      <%= f.input :category %>
      <%= f.input :allow_comments, :label => "Allow commenting on this article" %>
    <% end %>

    <%= f.inputs :name => "Advanced" do %>
      <%= f.input :keywords, :required => false, :hint => "Example: ruby, rails, forms" %>
      <%= f.input :extract, :required => false %>
      <%= f.input :description, :required => false %>
      <%= f.input :url_title, :required => false %>
    <% end %>

    <%= f.inputs :name => "Author", :for => :author do |author_form| %>
      <%= author_form.input :first_name %>
      <%= author_form.input :last_name %>
    <% end %>

    <%= f.actions do %>
      <%= f.action :submit, :as => :button %>
      <%= f.action :cancel, :as => :link %>
    <% end %>

  <% end %>

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/4 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.
  • It handles real world stuff like inline hints, inline error messages & help text.
  • It doesn't hijack or change any of the standard Rails form inputs, so you can still use them as expected (even mix and match).
  • It's got absolutely awesome spec coverage.
  • There's a bunch of people using and working on it (it's not just one developer building half a solution).
  • It has growing HTML5 support (new inputs like email/phone/search, new attributes like required/min/max/step/placeholder)

Opinions

  • It should be easier to do things the right way than the wrong way.
  • Sometimes more mark-up is better.
  • Elements and attribute hooks are gold for stylesheet authors.
  • Make the common things we do easy, yet ensure uncommon things are still possible.

Installation

Simply add Formtastic to your Gemfile and bundle it up:

  gem 'formtastic', '~> 3.0'

Run the installation generator:

$ rails generate formtastic:install

Stylesheets

A proof-of-concept set of stylesheets are provided which you can include in your layout. Customization is best achieved by overriding these styles in an additional stylesheet.

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.

  # app/assets/stylesheets/application.css
  *= require formtastic
  *= require my_formtastic_changes

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.

  # app/assets/stylesheets/ie6.css
  *= require formtastic_ie6

  # app/assets/stylesheets/ie7.css
  *= require formtastic_ie7
  # app/views/layouts/application.html.erb
  <%= stylesheet_link_tag 'application' %>
  <!--[if IE 6]><%= stylesheet_link_tag 'ie6' %><![endif]-->
  <!--[if IE 7]><%= stylesheet_link_tag 'ie7' %><![endif]-->
  # config/environments/production.rb
  config.assets.precompile += %w( ie6.css ie7.css )

Usage

Forms are really boring to code... you want to get onto the good stuff as fast as possible.

This renders a set of inputs (one for most columns in the database table, and one for each ActiveRecord belongs_to-association), followed by default action buttons (an input submit button):

  <%= semantic_form_for @user do |f| %>
    <%= f.inputs %>
    <%= f.actions %>
  <% end %>

This is a great way to get something up fast, but like scaffolding, it's not recommended for production. Don't be so lazy!

To specify the order of the fields, skip some of the fields or even add in fields that Formtastic couldn't infer. You can pass in a list of field names to inputs and list of action names to actions:

  <%= semantic_form_for @user do |f| %>
    <%= f.inputs :title, :body, :section, :categories, :created_at %>
    <%= f.actions :submit, :cancel %>
  <% end %>

You probably want control over the input type Formtastic uses for each field. You can expand the inputs and actions to block helper format and use the :as option to specify an exact input type:

  <%= semantic_form_for @post do |f| %>
    <%= f.inputs do %>
      <%= f.input :title %>
      <%= f.input :body %>
      <%= f.input :section, :as => :radio %>
      <%= f.input :categories %>
      <%= f.input :created_at, :as => :string %>
    <% end %>
    <%= f.actions do %>
      <%= f.action :submit, :as => :button %>
      <%= f.action :cancel, :as => :link %>
    <% end %>
  <% end %>

If you want to customize the label text, or render some hint text below the field, specify which fields are required/optional, or break the form into two fieldsets, the DSL is pretty comprehensive:

  <%= semantic_form_for @post do |f| %>
    <%= f.inputs "Basic", :id => "basic" do %>
      <%= f.input :title %>
      <%= f.input :body %>
    <% end %>
    <%= f.inputs :name => "Advanced Options", :id => "advanced" do %>
      <%= f.input :slug, :label => "URL Title", :hint => "Created automatically if left blank", :required => false %>
      <%= f.input :section, :as => :radio %>
      <%= f.input :user, :label => "Author" %>
      <%= f.input :categories, :required => false %>
      <%= f.input :created_at, :as => :string, :label => "Publication Date", :required => false %>
    <% end %>
    <%= f.actions do %>
      <%= f.action :submit %>
    <% end %>
  <% end %>

You can create forms for nested resources:

	<%= semantic_form_for [@author, @post] do |f| %>

Nested forms are also supported (don't forget your models need to be setup correctly with accepts_nested_attributes_for). You can do it in the Rails way:

  <%= semantic_form_for @post do |f| %>
    <%= f.inputs :title, :body, :created_at %>
    <%= f.semantic_fields_for :author do |author| %>
      <%= author.inputs :first_name, :last_name, :name => "Author" %>
    <% end %>
    <%= f.actions %>
  <% end %>

Or the Formtastic way with the :for option:

  <%= semantic_form_for @post do |f| %>
    <%= f.inputs :title, :body, :created_at %>
    <%= f.inputs :first_name, :last_name, :for => :author, :name => "Author" %>
    <%= f.actions %>
  <% end %>

When working in has many association, you can even supply "%i" in your fieldset name; they will be properly interpolated with the child index. For example:

  <%= semantic_form_for @post do |f| %>
    <%= f.inputs %>
    <%= f.inputs :name => 'Category #%i', :for => :categories %>
    <%= f.actions %>
  <% end %>

Alternatively, the current index can be accessed via the inputs block's arguments for use anywhere:

  <%= semantic_form_for @post do |f| %>
    <%= f.inputs :for => :categories do |category, i| %>
      ...
    <%= f.actions %>
  <% end %>

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:

  <%= semantic_form_for(@post, :namespace => 'cat_form') do |f| %>
    <%= f.inputs do %>
      <%= f.input :title %>        # id="cat_form_post_title"
      <%= f.input :body %>         # id="cat_form_post_body"
      <%= f.input :created_at %>   # id="cat_form_post_created_at"
    <% end %>
    <%= f.actions %>
  <% end %>

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:

  <%= semantic_form_for @post do |f| %>
    <%= f.inputs do %>
      <%= f.input :title,      :input_html => { :size => 10 } %>
      <%= f.input :body,       :input_html => { :class => 'autogrow', :rows => 10, :cols => 20, :maxlength => 10  } %>
      <%= f.input :created_at, :input_html => { :disabled => true } %>
      <%= f.input :updated_at, :input_html => { :readonly => true } %>
    <% end %>
    <%= f.actions %>
  <% end %>

The same can be done for actions with the :button_html option:

  <%= semantic_form_for @post do |f| %>
    ...
    <%= f.actions do %>
      <%= f.action :submit, :button_html => { :class => "primary", :disable_with => 'Wait...' } %>
    <% end %>
  <% end %>

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").

  <%= semantic_form_for @post do |f| %>
    <%= f.inputs do %>
      <%= f.input :title, :wrapper_html => { :class => "important" } %>
      <%= f.input :body %>
      <%= f.input :description, :wrapper_html => { :style => "display:none;" } %>
    <% end %>
    ...
  <% end %>

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:

  f.input :authors, :as => :check_boxes, :collection => User.order("last_name ASC").all
  f.input :authors, :as => :check_boxes, :collection => current_user.company.users.active
  f.input :authors, :as => :check_boxes, :collection => [@justin, @kate]
  f.input :authors, :as => :check_boxes, :collection => ["Justin", "Kate", "Amelia", "Gus", "Meg"]
  f.input :author,  :as => :select,      :collection => Author.all
  f.input :author,  :as => :select,      :collection => Author.pluck(:first_name, :id)
  f.input :author,  :as => :select,      :collection => Author.pluck(Arel.sql("CONCAT(`first_name`, ' ', `last_name`)"), :id)
  f.input :author,  :as => :select,      :collection => Author.your_custom_scope_or_class_method
  f.input :author,  :as => :select,      :collection => { @justin.name => @justin.id, @kate.name => @kate.id }
  f.input :author,  :as => :select,      :collection => ["Justin", "Kate", "Amelia", "Gus", "Meg"]
  f.input :author,  :as => :radio,       :collection => User.all
  f.input :author,  :as => :radio,       :collection => [@justin, @kate]
  f.input :author,  :as => :radio,