Forms made easy for Rails! It's tied to a simple DSL, with no opinion on markup.
Go to file
José Valim ee6cb1b818 Ready for prime time. 2010-02-06 19:26:39 +01:00
generators/simple_form_install Update TODO 2009-12-20 23:42:29 +01:00
lib Ready for prime time. 2010-02-06 19:26:39 +01:00
test Do not pass :include_blank for DateTime inputs neither for PriorityZones when a priority is defined. 2010-02-03 15:56:27 +01:00
.gitmodules Added :time_zone and :country select support. 2009-12-11 11:53:18 -02:00
CHANGELOG.rdoc Initial commit. 2009-11-18 15:45:35 -02:00
MIT-LICENSE Ready for prime time. 2010-02-06 19:26:39 +01:00
README.rdoc Ready for prime time. 2010-02-06 19:26:39 +01:00
Rakefile Ready for prime time. 2010-02-06 19:26:39 +01:00
TODO.rdoc Ready for prime time. 2010-02-06 19:26:39 +01:00
init.rb Base form helper and builder. 2009-11-18 21:50:43 -02:00
simple_form.gemspec Ready for prime time. 2010-02-06 19:26:39 +01:00

README.rdoc

== SimpleForm

Forms made easy (for Rails)!

SimpleForm aims to be as flexible as possible while helping you with powerful components to create your forms. The basic goal of simple form is to not touch your way of defining the layout, this way letting you find how you find the better design for your eyes. Good part of the DSL was inherited from Formtastic, which we are thankful for and should make you feel right at home.

== Installation

Install the gem:

  sudo gem install simple_form --version=1.0

Configure simple_form gem inside your app:

  config.gem 'simple_form'

Run the generator:

  ruby script/generate simple_form_install

And you're ready to go.

== Usage

SimpleForm was designed to be customized as you need to. Basically it's a stack of components that are invoked to create a complete html input for you, which by default contains label, hints, errors and the input itself. It does not aim to create a lot of different logic from the default Rails form helpers, as they do a great work by themselves. Instead, SimpleForm acts as a DSL and just maps your input type (retrieved from the column definition in the database) to an specific helper method.

To start using SimpleForm you just have to use the helper it provides:

  <% simple_form_for @user do |f| -%>
    <p><%= f.input :username %></p>
    <p><%= f.input :password %></p>
    <p><%= f.button :submit %></p>
  <% end -%>

This will generate an entire form with labels for user name and password as well, and render errors by default when you render the form with invalid data (after submitting for example).

You can overwrite the default label by passing it to the input method, or even add a hint:

  <% simple_form_for @user do |f| -%>
    <p><%= f.input :username, :label => 'Your username please' %></p>
    <p><%= f.input :password, :hint => 'No special characters.' %></p>
    <p><%= f.button :submit %></p>
  <% end -%>

You can also disable labels, hints or error or configure the html of any of them:

  <% simple_form_for @user do |f| -%>
    <p><%= f.input :username, :label_html => { :class => 'my_class' } %></p>
    <p><%= f.input :password, :hint => false, :error_html => { :id => "password_error"} %></p>
    <p><%= f.input :password_confirmation, :label => false %></p>
    <p><%= f.button :submit %></p>
  <% end -%>

By default all inputs are required, which means an * is prepended to the label, but you can disable it in any input you want:

  <% simple_form_for @user do |f| -%>
    <p><%= f.input :name, :required => false %></p>
    <p><%= f.input :username %></p>
    <p><%= f.input :password %></p>
    <p><%= f.button :submit %></p>
  <% end -%>

SimpleForm also lets you overwrite the default input type it creates:

  <% simple_form_for @user do |f| -%>
    <p><%= f.input :username %></p>
    <p><%= f.input :password %></p>
    <p><%= f.input :description, :as => :text %></p>
    <p><%= f.input :accepts,     :as => :radio %></p>
    <p><%= f.button :submit %></p>
  <% end -%>

So instead of a checkbox for the :accepts attribute, you'll have a pair of radio buttons with yes/no labels and a text area instead of a text field for the description. You can also render boolean attributes using :as => :select to show a dropdown.

SimpleForm also allows you using label, hint and error helpers it provides:

  <% simple_form_for @user do |f| -%>
    <p><%= f.label :username %></p>
    <p><%= f.text_field :username %></p>
    <p><%= f.error :username, :id => 'user_name_error' %></p>
    <p><%= f.hint 'No special characters, please!' %></p>
    <p><%= f.submit 'Save' %></p>
  <% end -%>

Any extra option passed to label, hint or error will be rendered as html option.

=== Collections

And what if you want to create a select containing the age from 18 to 60 in your form? You can do it overriding the :collection option:

  <% simple_form_for @user do |f| -%>
    <p><%= f.input :user %></p>
    <p><%= f.input :age, :collection => 18..60 %></p>
    <p><%= f.button :submit %></p>
  <% end -%>

Collections can be arrays or ranges, and when a :collection is given the :select input will be rendered by default, so we don't need to pass the :as => :select option. Other types of collection are :radio and :check_boxes. Those are added by SimpleForm to Rails set of form helpers (read Extra Helpers session below for more information).

Collection inputs accepts two other options beside collections:

* label_method => the label method to be applied to the collection to retrieve the label

* value_method => the value method to be applied to the collection to retrieve the value

Those methods are useful to manipulate the given collection. All other options given are sent straight to the underlying helper. For example, you can give prompt as:

  f.input :age, :collection => 18..60, :prompt => "Select your age"

=== Priority

SimpleForm also supports :time_zone and :country. When using such helpers, you can give :priority as option to select which time zones and/or countries should be given higher priority:

  f.input :residence_country, :priority => [ "Brazil" ]
  f.input :time_zone, :priority => /US/

Those values can also be configured with a default value to be used site use through the SimpleForm.country_priority and SimpleForm.time_zone_priority helpers.

=== Wrapper

SimpleForm allows you to add a wrapper which contains the label, error, hint and input.
The first step is to configure a wrapper tag:

  SimpleForm.wrapper_tag = :p

And now, you don't need to wrap your f.input calls with <p> anymore:

  <% simple_form_for @user do |f| -%>
    <%= f.input :username %>
    <%= f.input :password %>
    <p><%= f.button :submit %></p>
  <% end -%>

== Associations

To deal with associations, SimpleForm can generate select inputs or a series of radios or check boxes. Lets see how it works: imagine you have the user model that belongs to a company and has_and_belongs_to_many roles. The structure should be something like:

  class User < ActiveRecord::Base
    belongs_to :company
    has_and_belongs_to_many :roles
  end

  class Company < ActiveRecord::Base
    has_many :users
  end

  class Role < ActiveRecord::Base
    has_and_belongs_to_many :users
  end

Now we have the user form:

  <% simple_form_for @user do |f| -%>
    <p><%= f.input :name %></p>
    <p><%= f.association :company %></p>
    <p><%= f.association :roles %></p>
    <p><%= f.button :submit %></p>
  <% end -%>

Simple enough right? This is going to render a :select input for choosing the :company, and another :select input with :multiple option for the :roles. You can of course change it, to use radios and check boxes as well:

    f.association :company, :as => :radio
    f.association :roles, :as => :check_boxes

And you will get a set of radios to select the company and another set of check boxes for the roles. Some options are available for refining the collection for associations: :conditions, :include, :joins, :order. These options are given straight to the find method. Here is an example of how to use these options:

  f.association :company, :order => 'name'
  f.association :roles, :conditions => { :active => true }

You also have the ability to call named scopes using the association:

  f.association :company, :scope => [:active, :available]

The association helper just invokes input under the hood, so all options available to :select, :radio and :check_boxes are also available to association. For example, you can specify the collection by hand, all together with the prompt:

  f.association :company, :collection => Company.active.all(:order => 'name'), :prompt => "Choose a Company"

== Buttons

All web forms need buttons, right? To help you with this, SimpleForm has a default button helper that acts as a wrapper for Rails helpers, creating submit texts using I18n. It's pretty straightforward:

  <% simple_form_for @user do |f| -%>
    <p><%= f.input :name %></p>
    <p><%= f.button :submit %></p>
  <% end -%>

This will create a input submit tag for you. If the resource @user is a new record, the button will have text 'Create User', otherwise 'Update User' is shown. If you are working with forms without objects, 'Submit User' would be shown. All those buttons labels can be configured using I18n through the keys :simple_form.buttons.create, :simple_form.buttons.update and :simple_form.buttons.submit.

You can also pass the button text directly:

  f.button :submit, 'Save User'
  f.button :submit, :label => 'Save User'

As button is just a wrapper, it is actually calling Rails helper :submit_tag with the provided text. That said, any other option you pass will be given to :submit_tag call:

  f.button :submit, :confirm => 'Are you sure?'

And if you want to use any other button tag, you just need to create a helper that ends with "_tag":

  # inside ApplicationHelper for instance
  def custom_submit_tag(text, options={})
    # render submit tag here
  end

And you will able to use it with SimpleForm:

  f.button :custom_submit

== Extra helpers

SimpleForm also comes with some extra helpers you can use inside rails default forms without relying on simple_form_for helper. They are listed below.

=== Simple Fields For

Wrapper to use simple form inside a default rails form

  form_for @user do |f|
    f.simple_fields_for :posts do |posts_form|
      # Here you have all simple_form methods available
      posts_form.input :title
    end
  end

=== Collection Radio

Creates a collection of radio inputs with labels associated (same API as collection_select):

  form_for @user do |f|
    f.collection_radio :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
  end

  <input id="user_options_true" name="user[options]" type="radio" value="true" />
  <label class="collection_radio" for="user_options_true">Yes</label>
  <input id="user_options_false" name="user[options]" type="radio" value="false" />
  <label class="collection_radio" for="user_options_false">No</label>

=== Collection Check Box

Creates a collection of check boxes with labels associated (same API as collection_select):

  form_for @user do |f|
    f.collection_check_box :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
  end

  <input name="user[options][]" type="hidden" value="" />
  <input id="user_options_true" name="user[options][]" type="checkbox" value="true" />
  <label class="collection_check_box" for="user_options_true">Yes</label>
  <input name="user[options][]" type="hidden" value="" />
  <input id="user_options_false" name="user[options][]" type="checkbox" value="false" />
  <label class="collection_check_box" for="user_options_false">No</label>

== Mappings/Inputs available

SimpleForm comes with a lot of default mappings:

  Mapping               Input                   Column Type

  boolean               check box               boolean
  string                text field              string
  password              password field          string with name matching "password"
  text                  text area               text
  file                  file field              string, responding to file methods
  hidden                hidden field            -
  integer               text field              integer
  float                 text field              float
  decimal               text field              decimal
  datetime              datetime select         datetime/timestamp
  date                  date select             date
  time                  time select             time
  select                collection select       belongs_to/has_many/has_and_belongs_to_many associations
  radio                 collection radio        belongs_to
  check_boxes           collection check box    has_many/has_and_belongs_to_many associations
  country               country select          string with name matching "country"
  time_zone             time zone select        string with name matching "time_zone"

== I18n

SimpleForm uses all power of I18n API to lookup labels and hints for you. To customize your forms you can create a locale file like this:

  en:
    simple_form:
      labels:
        user:
          username: 'User name'
          password: 'Password'
      hints:
        user:
          username: 'User name to sign in.'
          password: 'No special characters, please.'

And your forms will use this information to render labels and hints for you.

SimpleForm also lets you be more specific, separating lookups through actions for both hint and label. Let's say you want a different label for new and edit actions, the locale file would be something like:

  en:
    simple_form:
      labels:
        user:
          username: 'User name'
          password: 'Password'
          edit:
            username: 'Change user name'
            password: 'Change password'

This way SimpleForm will figure out the right translation for you, based on the action being rendered. And to be a little bit DRYer with your locale file, you can skip the model information inside it:

  en:
    simple_form:
      labels:
        username: 'User name'
        password: 'Password'
      hints:
        username: 'User name to sign in.'
        password: 'No special characters, please.'

SimpleForm will always look for a default attribute translation if no specific is found inside the model key. In addition, SimpleForm will fallback to default human_attribute_name from Rails when no other translation is found.

Finally, you can also overwrite labels and hints inside your view, just by passing the label/hint manually. This way the I18n lookup will be skipped.

There are other options that can be configured through I18n API, such as required text, boolean and button texts. Be sure to check our locale file or the one copied to your application after you run "script/generate simple_form_install".

== Configuration

SimpleForm has several configuration values. You can read and change them in the initializer created by SimpleForm, so if you haven't executed the command below yet, please do:

  ruby script/generate simple_form_install

== TODO

Please refer to TODO file.

== Maintainers

* José Valim (http://github.com/josevalim)
* Carlos Antonio da Silva (http://github.com/carlosantoniodasilva)

== Bugs and Feedback

If you discover any bugs or want to drop a line, feel free to create an issue on GitHub.

http://github.com/plataformatec/simple_form/issues

MIT License. Copyright 2010 Plataforma Tecnologia. http://blog.plataformatec.com.br