now available

now available
Want fresh tech tips in your inbox?

Using Formtastic to Cleanly Create Nice Looking Forms in Rails


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 w/ #dsl #forms #formtastic #rubyruby on rails

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app