h1. Formtastic

!travis-ci.org/justinfrench/formtastic.png?branch=master!:https://travis-ci.org/justinfrench/formtastic !inch-ci.org/github/justinfrench/formtastic.png!:http://inch-ci.org/github/justinfrench/formtastic !codeclimate.com/github/justinfrench/formtastic.png!:https://codeclimate.com/github/justinfrench/formtastic !badge.fury.io/rb/formtastic.png!:http://badge.fury.io/rb/formtastic !gemnasium.com/justinfrench/formtastic.png!:https://gemnasium.com/justinfrench/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.

h2. Documentation & Support

h2. Compatibility

h2. 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:

<pre>

<%= 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 %>

</pre>

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”:www.slideshare.net/AaronGustafson/learning-to-love-forms-web-directions-south-07, hacking together enough Ruby to prove it could be done.

h2. It's awesome because…

h2. Opinions

h2. Installation

Simply add Formtastic to your Gemfile and bundle it up:

<pre>

gem 'formtastic', '~> 3.0'

</pre>

Run the installation generator:

<pre lang=shell>

$ rails generate formtastic:install

</pre>

h2. 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.

<pre>

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

</pre>

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.

<pre>

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

# app/assets/stylesheets/ie7.css
*= require formtastic_ie7

</pre>

<pre>

# 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]-->

</pre>

<pre>

# config/environments/production.rb
config.assets.precompile += %w( ie6.css ie7.css )

</pre>

h2. 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):

<pre>

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

</pre>

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@:

<pre>

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

</pre>

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:

<pre>

<%= 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 %>

</pre>

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:

<pre>

<%= 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 %>

</pre>

You can create forms for nested resources:

<pre>

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

</pre>

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:

<pre>

<%= 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 %>

</pre>

Or the Formtastic way with the @:for@ option:

<pre>

<%= 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 %>

</pre>

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:

<pre>

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

</pre>

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

<pre>

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

</pre>

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:

<pre>

<%= 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 %>

</pre>

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”:plugins.jquery.com/project/autogrowtextarea textareas:

<pre>

<%= 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 %>

</pre>

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

<pre>

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

</pre>

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”@).

<pre>

<%= 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 %>

</pre>

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:

<pre>

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,       :collection => { @justin.name => @justin.id, @kate.name => @kate.id }
f.input :author,  :as => :radio,       :collection => ["Justin", "Kate", "Amelia", "Gus", "Meg"]
f.input :admin,   :as => :radio,       :collection => ["Yes!", "No"]
f.input :book_id, :as => :select,      :collection => Hash[Book.all.map{|b| [b.name,b.id]}]
f.input :fav_book,:as => :datalist   , :collection => Book.pluck(:name)

</pre>

h2. The Available Inputs

The Formtastic input types:

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.

h2. Delegation for label lookups

Formtastic decides which label to use in the following order:

<pre>

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

</pre>

h2. Internationalization (I18n)

h3. 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.

Basic localization (labels only, with ActiveRecord):

<pre>

<%= semantic_form_for @post do |f| %>
  <%= f.inputs do %>
    <%= f.input :title %>        # => :label => I18n.t('activerecord.attributes.user.title')    or 'Title'
    <%= f.input :body %>         # => :label => I18n.t('activerecord.attributes.user.body')     or 'Body'
    <%= f.input :section %>      # => :label => I18n.t('activerecord.attributes.user.section')  or 'Section'
  <% end %>
<% end %>

</pre>

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?

h3. 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:

*1. Enable I18n lookups by default (@config/initializers/formtastic.rb@):*

<pre>

Formtastic::FormBuilder.i18n_lookups_by_default = true

</pre>

*2. Add some label-translations/variants (@config/locales/en.yml@):*

<pre>

en:
  formtastic:
    titles:
      post_details: "Post details"
    labels:
      post:
        title: "Your Title"
        body: "Write something..."
        edit:
          title: "Edit title"
    hints:
      post:
        title: "Choose a good title for your post."
        body: "Write something inspiring here."
    placeholders:
      post:
        title: "Title your post"
        slug: "Leave blank for an automatically generated slug"
      user:
        email: "you@yours.com"
    actions:
      create: "Create my %{model}"
      update: "Save changes"
      reset: "Reset form"
      cancel: "Cancel and go back"
      dummie: "Launch!"

</pre>

*3. …and now you'll get:*

<pre>

<%= semantic_form_for Post.new do |f| %>
  <%= f.inputs do %>
    <%= f.input :title %>      # => :label => "Choose a title...", :hint => "Choose a good title for your post."
    <%= f.input :body %>       # => :label => "Write something...", :hint => "Write something inspiring here."
    <%= f.input :section %>    # => :label => I18n.t('activerecord.attributes.user.section')  or 'Section'
  <% end %>
  <%= f.actions do %>
    <%= f.action :submit %>   # => "Create my %{model}"
  <% end %>
<% end %>

</pre>

*4. Localized titles (a.k.a. legends):*

_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._

<pre>

<%= semantic_form_for @post do |f| %>
  <%= f.inputs :post_details do %>   # => :title => "Post details"
    # ...
  <% end %>
  # ...

<% end %> </pre>

*5. Override I18n settings:*

<pre>

<%= semantic_form_for @post do |f| %>
  <%= f.inputs do %>
    <%= f.input :title %>      # => :label => "Choose a title...", :hint => "Choose a good title for your post."
    <%= f.input :body, :hint => false %>                 # => :label => "Write something..."
    <%= f.input :section, :label => 'Some section' %>    # => :label => 'Some section'
  <% end %>
  <%= f.actions do %>
    <%= f.action :submit, :label => :dummie %>         # => "Launch!"
  <% end %>
<% end %>

</pre>

If I18n-lookups is disabled, i.e.:

<pre>

Formtastic::FormBuilder.i18n_lookups_by_default = false

</pre>

…then you can enable I18n within the forms instead:

<pre>

<%= semantic_form_for @post do |f| %>
  <%= f.inputs do %>
    <%= f.input :title, :label => true %>      # => :label => "Choose a title..."
    <%= f.input :body, :label => true %>       # => :label => "Write something..."
    <%= f.input :section, :label => true %>    # => :label => I18n.t('activerecord.attributes.user.section')  or 'Section'
  <% end %>
  <%= f.actions do %>
    <%= f.action :submit, :label => true %>    # => "Update %{model}" (if we are in edit that is...)
  <% end %>
<% end %>

</pre>

*6. Advanced I18n lookups*

For more flexible forms; Formtastic finds translations using a bottom-up approach taking the following variables in account:

…in the following order:

  1. @formtastic.{titles,labels,hints,actions}.MODEL.ACTION.ATTRIBUTE@ - by model and action

  2. @formtastic.{titles,labels,hints,actions}.MODEL.ATTRIBUTE@ - by model

  3. @formtastic.{titles,labels,hints,actions}.ATTRIBUTE@ - global default

…which means that you can define translations like this:

<pre>

en:
  formtastic:
    labels:
      title: "Title"  # Default global value
      article:
        body: "Article content"
      post:
        new:
          title: "Choose a title..."
          body: "Write something..."
        edit:
          title: "Edit title"
          body: "Edit body"

</pre>

Values for @labels@/@hints@/@actions@ are can take values: @String@ (explicit value), @Symbol@ (i18n-lookup-key relative to the current “type”, e.g. actions:), @true@ (force I18n lookup), @false@ (force no I18n lookup). Titles (legends) can only take: @String@ and @Symbol@ - true/false have no meaning.

*7. Basic Translations* If you want some basic translations, take a look on the “formtastic_i18n gem”:github.com/timoschilling/formtastic_i18n.

h2. Semantic errors

You can show errors on base (by default) and any other attribute just by passing its name to the semantic_errors method:

<pre>

<%= semantic_form_for @post do |f| %>
  <%= f.semantic_errors :state %>
<% end %>

</pre>

h2. Modified & Custom Inputs

You can modify existing inputs, subclass them, or create your own from scratch. Here's the basic process:

Specific examples follow.

h3. Changing Existing Input Behavior

To modify the behavior of @StringInput@, subclass it in a new file, @app/inputs/string_input.rb@:

<pre>

class StringInput < Formtastic::Inputs::StringInput
  def to_html
    puts "this is my modified version of StringInput"
    super
  end
end

</pre>

You can use your modified version with @:as => :string@.

h3. 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@:

<pre>

class FlexibleTextInput < Formtastic::Inputs::StringInput
  def input_html_options
    super.merge(:class => "flexible-text-area")
  end
end

</pre>

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

h3. Creating New Inputs From Scratch

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

<pre>

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

</pre>

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

h2. Dependencies

There are none other than Rails itself, but…

h2. How to contribute

h2. Project Info

Formtastic was created by “Justin French”:www.justinfrench.com with contributions from around 180 awesome developers. Run @git shortlog -n -s@ to see the awesome.

The project is hosted on Github: “github.com/justinfrench/formtastic”:http://github.com/justinfrench/formtastic, where your contributions, forkings, comments, issues and feedback are greatly welcomed.

Copyright © 2007-2014 Justin French, released under the MIT license.