Bootstrap 5
Simple Form can be easily integrated with Bootstrap 5.
Use the bootstrap
option in the install generator, like this:
rails generate simple_form:install --bootstrap
This will add an initializer that configures Simple Form wrappers for Bootstrap 5’s form controls. You have to be sure that you added a copy of the Bootstrap assets on your application.
For more information see the generator output, our example application code and the live example app.
Country Select
If you want to use the country select, you will need the country_select gem, add it to your Gemfile:
gem 'country_select'
If you don’t want to use the gem you can easily override this behaviour by mapping the
country inputs to something else, with a line like this in your simple_form.rb
initializer:
config.input_mappings = { /country/ => :string }
Stripping away all wrapper divs
Simple Form also allows you to strip away all the div wrappers around the <input>
field that is
generated with the usual f.input
.
The easiest way to achieve this is to use f.input_field
.
Example:
simple_form_for @user do |f|
f.input_field :name
f.input_field :remember_me, as: :boolean
end
<form>
...
<input class="string required" id="user_name" maxlength="255" name="user[name]" size="255" type="text">
<input name="user[remember_me]" type="hidden" value="0">
<label class="checkbox">
<input class="boolean optional" id="user_published" name="user[remember_me]" type="checkbox" value="1">
</label>
</form>
For check boxes and radio buttons you can remove the label changing boolean_style
from default value :nested
to :inline
.
Example:
simple_form_for @user do |f|
f.input_field :name
f.input_field :remember_me, as: :boolean, boolean_style: :inline
end
<form>
...
<input class="string required" id="user_name" maxlength="255" name="user[name]" size="255" type="text">
<input name="user[remember_me]" type="hidden" value="0">
<input class="boolean optional" id="user_remember_me" name="user[remember_me]" type="checkbox" value="1">
</form>
To view the actual RDocs for this, check them out here - http://rubydoc.info/github/heartcombo/simple_form/main/SimpleForm/FormBuilder:input_field
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| %>
<%= f.input :user %>
<%= f.input :age, collection: 18..60 %>
<%= f.button :submit %>
<% 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_buttons
and :check_boxes
. Those are added by Simple Form to Rails set of form
helpers (read Extra Helpers section below for more information).
Collection inputs accept two other options beside collections:
label_method => the label method to be applied to the collection to retrieve the label (use this instead of the
text_method
option incollection_select
)value_method => the value method to be applied to the collection to retrieve the value
Those methods are useful to manipulate the given collection. Both of these options also accept
lambda/procs in case you want to calculate the value or label in a special way eg. custom
translation. You can also define a to_label
method on your model as Simple Form will search for
and use :to_label
as a :label_method
first if it is found.
By default, Simple Form will use the first item from an array as the label and the second one as the value. If you want to change this behavior you must make it explicit, like this:
<%= simple_form_for @user do |f| %>
<%= f.input :gender, as: :radio_buttons, collection: [['0', 'female'], ['1', 'male']], label_method: :second, value_method: :first %>
<% end %>
All other options given are sent straight to the underlying Rails helper(s): collection_select
, collection_check_boxes
, collection_radio_buttons
. For example, you can pass prompt
and selected
as:
f.input :age, collection: 18..60, prompt: "Select your age", selected: 21
It may also be useful to explicitly pass a value to the optional :selected
like above, especially if passing a collection of nested objects.
It is also possible to create grouped collection selects, that will use the html optgroup tags, like this:
f.input :country_id, collection: @continents, as: :grouped_select, group_method: :countries
Grouped collection inputs accept the same :label_method
and :value_method
options, which will be
used to retrieve label/value attributes for the option
tags. Besides that, you can give:
group_method => the method to be called on the given collection to generate the options for each group (required)
group_label_method => the label method to be applied on the given collection to retrieve the label for the optgroup (Simple Form will attempt to guess the best one the same way it does with
:label_method
)
Associations
To deal with associations, Simple Form can generate select inputs, a series of radios buttons or checkboxes.
Lets see how it works: imagine you have a user model that belongs to a company and has_and_belongs_to_many
roles. The structure would 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| %>
<%= f.input :name %>
<%= f.association :company %>
<%= f.association :roles %>
<%= f.button :submit %>
<% 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 radio
buttons and checkboxes as well:
f.association :company, as: :radio_buttons
f.association :roles, as: :check_boxes
The association helper just invokes input
under the hood, so all options available to :select
,
:radio_buttons
and :check_boxes
are also available to association. Additionally, you can specify
the collection by hand, all together with the prompt:
f.association :company, collection: Company.active.order(:name), prompt: "Choose a Company"
In case you want to declare different labels and values:
f.association :company, label_method: :company_name, value_method: :id, include_blank: false
Please note that the association helper is currently only tested with Active Record. It currently does not work well with Mongoid and depending on the ORM you’re using your mileage may vary.
Buttons
All web forms need buttons, right? Simple Form wraps them in the DSL, acting like a proxy:
<%= simple_form_for @user do |f| %>
<%= f.input :name %>
<%= f.button :submit %>
<% end %>
The above will simply call submit. You choose to use it or not, it’s just a question of taste.
The button method also accepts optional parameters, that are delegated to the underlying submit call:
<%= f.button :submit, "Custom Button Text", class: "my-button" %>
To create a <button>
element, use the following syntax:
<%= f.button :button, "Custom Button Text" %>
<%= f.button :button do %>
Custom Button Text
<% end %>
Wrapping Rails Form Helpers
Say you wanted to use a rails form helper but still wrap it in Simple Form goodness? You can, by calling input with a block like so:
<%= f.input :role do %>
<%= f.select :role, Role.all.map { |r| [r.name, r.id, { class: r.company.id }] }, include_blank: true %>
<% end %>
In the above example, we’re taking advantage of Rails 3’s select method that allows us to pass in a hash of additional attributes for each option.
Extra helpers
Simple Form 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. It works in the same way that the fields_for
Rails helper, but change the builder to use the SimpleForm::FormBuilder
.
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 Buttons
Creates a collection of radio inputs with labels associated (same API as collection_select
):
form_for @user do |f|
f.collection_radio_buttons :options, [[true, 'Yes'], [false, 'No']], :first, :last
end
<input id="user_options_true" name="user[options]" type="radio" value="true" />
<label class="collection_radio_buttons" for="user_options_true">Yes</label>
<input id="user_options_false" name="user[options]" type="radio" value="false" />
<label class="collection_radio_buttons" for="user_options_false">No</label>
Collection Check Boxes
Creates a collection of checkboxes with labels associated (same API as collection_select
):
form_for @user do |f|
f.collection_check_boxes :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>
To use this with associations in your model, you can do the following:
form_for @user do |f|
f.collection_check_boxes :role_ids, Role.all, :id, :name # using :roles here is not going to work.
end
To add a CSS class to the label item, you can use the item_label_class
option:
f.collection_check_boxes :role_ids, Role.all, :id, :name, item_label_class: 'my-custom-class'
Available input types and defaults for each column type
The following table shows the html element you will get for each attribute
according to its database definition. These defaults can be changed by
specifying the helper method in the column Mapping
as the as:
option.
Mapping | Generated HTML Element | Database Column Type |
---|---|---|
boolean |
input[type=checkbox] |
boolean |
string |
input[type=text] |
string |
citext |
input[type=text] |
citext |
email |
input[type=email] |
string with name =~ /email/ |
url |
input[type=url] |
string with name =~ /url/ |
tel |
input[type=tel] |
string with name =~ /phone/ |
password |
input[type=password] |
string with name =~ /password/ |
search |
input[type=search] |
- |
uuid |
input[type=text] |
uuid |
color |
input[type=color] |
string |
text |
textarea |
text |
hstore |
textarea |
hstore |
json |
textarea |
json |
jsonb |
textarea |
jsonb |
file |
input[type=file] |
string responding to file methods |
hidden |
input[type=hidden] |
- |
integer |
input[type=number] |
integer |
float |
input[type=number] |
float |
decimal |
input[type=number] |
decimal |
range |
input[type=range] |
- |
datetime |
datetime select |
datetime/timestamp |
date |
date select |
date |
time |
time select |
time |
select |
select |
belongs_to /has_many /has_and_belongs_to_many associations |
radio_buttons |
collection of input[type=radio] |
belongs_to associations |
check_boxes |
collection of input[type=checkbox] |
has_many /has_and_belongs_to_many associations |
country |
select (countries as options) |
string with name =~ /country/ |
time_zone |
select (timezones as options) |
string with name =~ /time_zone/ |
rich_text_area |
trix-editor |
- |
Custom inputs
It is very easy to add custom inputs to Simple Form. For instance, if you want to add a custom input that extends the string one, you just need to add this file:
# app/inputs/currency_input.rb
class CurrencyInput < SimpleForm::Inputs::Base
def input(wrapper_options)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
"$ #{@builder.text_field(attribute_name, merged_input_options)}".html_safe
end
end
And use it in your views:
f.input :money, as: :currency
Note, you may have to create the app/inputs/
directory and restart your webserver.
You can also redefine existing Simple Form inputs by creating a new class with the same name. For instance, if you want to wrap date/time/datetime in a div, you can do:
# app/inputs/date_time_input.rb
class DateTimeInput < SimpleForm::Inputs::DateTimeInput
def input(wrapper_options)
template.content_tag(:div, super)
end
end
Or if you want to add a class to all the select fields you can do:
# app/inputs/collection_select_input.rb
class CollectionSelectInput < SimpleForm::Inputs::CollectionSelectInput
def input_html_classes
super.push('chosen')
end
end
If needed, you can namespace your custom inputs in a module and tell Simple Form to look for their definitions in this module. This can avoid conflicts with other form libraries (like Formtastic) that look up the global context to find inputs definition too.
# app/inputs/custom_inputs/numeric_input
module CustomInputs
class NumericInput < SimpleForm::Inputs::NumericInput
def input_html_classes
super.push('no-spinner')
end
end
end
And in the SimpleForm initializer :
# config/simple_form.rb
config.custom_inputs_namespaces << "CustomInputs"
Custom form builder
You can create a custom form builder that uses Simple Form.
Create a helper method that calls simple_form_for
with a custom builder:
def custom_form_for(object, *args, &block)
options = args.extract_options!
simple_form_for(object, *(args << options.merge(builder: CustomFormBuilder)), &block)
end
Create a form builder class that inherits from SimpleForm::FormBuilder
.
class CustomFormBuilder < SimpleForm::FormBuilder
def input(attribute_name, options = {}, &block)
super(attribute_name, options.merge(label: false), &block)
end
end
Configuration
Simple Form has several configuration options. You can read and change them in the initializer created by Simple Form, so if you haven’t executed the command below yet, please do:
rails generate simple_form:install
The wrappers API
With Simple Form you can configure how your components will be rendered using the wrappers API. The syntax looks like this:
config.wrappers tag: :div, class: :input,
error_class: :field_with_errors,
valid_class: :field_without_errors do |b|
# Form extensions
b.use :html5
b.optional :pattern
b.use :maxlength
b.use :placeholder
b.use :readonly
# Form components
b.use :label_input
b.use :hint, wrap_with: { tag: :span, class: :hint }
b.use :error, wrap_with: { tag: :span, class: :error }
end
The Form components will generate the form tags like labels, inputs, hints or errors contents. The available components are:
:label # The <label> tag alone
:input # The <input> tag alone
:label_input # The <label> and the <input> tags
:hint # The hint for the input
:error # The error for the input
The Form extensions are used to generate some attributes or perform some lookups on the model to add extra information to your components.
You can create new Form components using the wrappers API as in the following example:
config.wrappers do |b|
b.use :placeholder
b.use :label_input
b.wrapper tag: :div, class: 'separator' do |component|
component.use :hint, wrap_with: { tag: :span, class: :hint }
component.use :error, wrap_with: { tag: :span, class: :error }
end
end
this will wrap the hint and error components within a div
tag using the class 'separator'
.
You can customize Form components passing options to them:
config.wrappers do |b|
b.use :label_input, class: 'label-input-class', error_class: 'is-invalid', valid_class: 'is-valid'
end
This sets the input and label classes to 'label-input-class'
and will set the class 'is-invalid'
if the input has errors and 'is-valid'
if the input is valid.
If you want to customize the custom Form components on demand you can give it a name like this:
config.wrappers do |b|
b.use :placeholder
b.use :label_input
b.wrapper :my_wrapper, tag: :div, class: 'separator', html: { id: 'my_wrapper_id' } do |component|
component.use :hint, wrap_with: { tag: :span, class: :hint }
component.use :error, wrap_with: { tag: :span, class: :error }
end
end
and now you can pass options to your input
calls to customize the :my_wrapper
Form component.
# Completely turns off the custom wrapper
f.input :name, my_wrapper: false
# Configure the html
f.input :name, my_wrapper_html: { id: 'special_id' }
# Configure the tag
f.input :name, my_wrapper_tag: :p
You can also define more than one wrapper and pick one to render in a specific form or input. To define another wrapper you have to give it a name, as the follow:
config.wrappers :small do |b|
b.use :placeholder
b.use :label_input
end
and use it in this way:
# Specifying to whole form
simple_form_for @user, wrapper: :small do |f|
f.input :name
end
# Specifying to one input
simple_form_for @user do |f|
f.input :name, wrapper: :small
end
Simple Form also allows you to use optional elements. For instance, let’s suppose you want to use
hints or placeholders, but you don’t want them to be generated automatically. You can set their
default values to false
or use the optional
method. Is preferable to use the optional
syntax:
config.wrappers placeholder: false do |b|
b.use :placeholder
b.use :label_input
b.wrapper tag: :div, class: 'separator' do |component|
component.optional :hint, wrap_with: { tag: :span, class: :hint }
component.use :error, wrap_with: { tag: :span, class: :error }
end
end
By setting it as optional
, a hint will only be generated when hint: true
is explicitly used.
The same for placeholder.
It is also possible to give the option :unless_blank
to the wrapper if you want to render it only
when the content is present.
b.wrapper tag: :span, class: 'hint', unless_blank: true do |component|
component.optional :hint
end
Custom Components
When you use custom wrappers, you might also be looking for a way to add custom components to your wrapper. The default components are:
:label # The <label> tag alone
:input # The <input> tag alone
:label_input # The <label> and the <input> tags
:hint # The hint for the input
:error # The error for the input
A custom component might be interesting for you if your views look something like this:
<%= simple_form_for @blog do |f| %>
<div class="row">
<div class="span1 number">
1
</div>
<div class="span8">
<%= f.input :title %>
</div>
</div>
<div class="row">
<div class="span1 number">
2
</div>
<div class="span8">
<%= f.input :body, as: :text %>
</div>
</div>
<% end %>
A cleaner method to create your views would be:
<%= simple_form_for @blog, wrapper: :with_numbers do |f| %>
<%= f.input :title, number: 1 %>
<%= f.input :body, as: :text, number: 2 %>
<% end %>
To use the number option on the input, first, tells to Simple Form the place where the components will be:
# config/initializers/simple_form.rb
Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f }
Create a new component within the path specified above:
# lib/components/numbers_component.rb
module NumbersComponent
# To avoid deprecation warning, you need to make the wrapper_options explicit
# even when they won't be used.
def number(wrapper_options = nil)
@number ||= begin
options[:number].to_s.html_safe if options[:number].present?
end
end
end
SimpleForm.include_component(NumbersComponent)
Finally, add a new wrapper to the config/initializers/simple_form.rb file:
config.wrappers :with_numbers, tag: 'div', class: 'row', error_class: 'error' do |b|
b.use :html5
b.use :number, wrap_with: { tag: 'div', class: 'span1 number' }
b.wrapper tag: 'div', class: 'span8' do |ba|
ba.use :placeholder
ba.use :label
ba.use :input
ba.use :error, wrap_with: { tag: 'span', class: 'help-inline' }
ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
end
Using non Active Record objects
There are few ways to build forms with objects that don’t inherit from Active Record, as follows:
You can include the module ActiveModel::Model
.
class User
include ActiveModel::Model
attr_accessor :id, :name
end
If you are using Presenters or Decorators that inherit from SimpleDelegator
you can delegate
it to the model.
class UserPresenter < SimpleDelegator
# Without that, Simple Form will consider the user model as the object.
def to_model
self
end
end
You can define all methods required by the helpers.
class User
extend ActiveModel::Naming
attr_accessor :id, :name
def to_model
self
end
def to_key
id
end
def persisted?
false
end
end
To have SimpleForm infer the attributes’ types, you can provide
#has_attribute?
and #type_for_attribute
methods.
The later should return an object that responds to #type
with the attribute type. This is useful for generating
the correct input types (eg: checkboxes for booleans).
class User < Struct.new(:id, :name, :age, :registered)
def to_model
self
end
def model_name
OpenStruct.new(param_key: "user")
end
def to_key
id
end
def persisted?
id.present?
end
def has_attribute?(attr_name)
%w(id name age registered).include?(attr_name.to_s)
end
def type_for_attribute(attr_name)
case attr_name.to_s
when "id" then OpenStruct.new(type: :integer)
when "name" then OpenStruct.new(type: :string)
when "age" then OpenStruct.new(type: :integer)
when "registered" then OpenStruct.new(type: :boolean)
end
end
end
If your object doesn’t implement those methods, you must make explicit it when you are building the form
class User
attr_accessor :id, :name
# The only method required to use the f.submit helper.
def persisted?
false
end
end
<%= simple_form_for(@user, as: :user, method: :post, url: users_path) do |f| %>
<%= f.input :name %>
<%= f.submit 'New user' %>
<% end %>
Information
RDocs
You can view the Simple Form documentation in RDoc format here:
http://rubydoc.info/github/heartcombo/simple_form/main/frames
Bug reports
If you discover any bugs, feel free to create an issue on GitHub. Please add as much information as possible to help us in fixing the potential bug. We also encourage you to help even more by forking and sending us a pull request.
https://github.com/heartcombo/simple_form/issues
If you have discovered a security related bug, please do NOT use the GitHub issue tracker. Send an e-mail to heartcombo@googlegroups.com.
Maintainers
- Carlos Antonio da Silva (https://github.com/carlosantoniodasilva)
- Rafael Mendonça França (https://github.com/rafaelfranca)
- Felipe Renan (https://github.com/feliperenan)