Written by Sean Behan on Sun Jun 17th 2012

Forms can easily get cluttered when you're dealing with a lot of form fields... er, ERB tags. I've written about extending Rails form builders, which certainly goes along way to shrinking your views where forms are used. The plugin Formtastic is even better, as it lets you skirt maintaining your own library in favor of a very, elegant DSL.

For a great overview of the plugin and implementation details, check out Ryan Bate's Railscast. There are a couple episodes, but be sure to catch the first one, linked above.

I usually install the plugin as a gem

# config/environment.rb
config.gem "formtastic"
and then run a generator to create the stylesheets for me, making forms look nice and neat.
./script/generate formtastic
One gotcha, is that in order for the css to render correctly you need to add this
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
in the head of your layout file.

You define forms usingĀ  "semantic_form_for" like so...

<% semantic_form_for @user do |f| %>
  <% f.inputs do %>
    <%= f.input :login, :label => "Username", :hint => "Something short because it's in the url"%>
  <% end %>
  <%= f.buttons %>
<% end %>

As per usual, there are a myriad of configuration options which can be overridden if necessary. Consult the documentation at Justin French's Github account for specifics.

Tagged with..
#dsl #forms #formtastic #ruby #Ruby on Rails

Just finishing up brewing up some fresh ground comments...