- Notifications
You must be signed in to change notification settings - Fork0
Forms made easy for Rails! It's tied to a simple DSL, with no opinion on markup.
License
JuanVqz/simple_form
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Rails forms made easy.
Simple Form aims to be as flexible as possible while helping you with powerful components to createyour forms. The basic goal ofSimple Form is to not touch your way of defining the layout, lettingyou find the better design for your eyes. Most of the DSL was inherited from Formtastic,which we are thankful for and should make you feel right at home.
INFO: This README refers toSimple Form 5.0. For older releases, check the related branch for your version.
- Installation
- Usage
- Available input types and defaults for each column type
- Custom inputs
- Custom form builder
- I18n
- Configuration
- Custom Components
- HTML 5 Notice
- Information
- Maintainers
- License
Add it to your Gemfile:
gem'simple_form'
Run the following command to install it:
bundle install
Run the generator:
rails generate simple_form:install
Simple Form can be easily integrated withBootstrap 5.Use thebootstrap
option in the install generator, like this:
rails generate simple_form:install --bootstrap
This will add an initializer that configuresSimple Form wrappers forBootstrap 5'sform controls.You have to be sure that you added a copy of theBootstrapassets on your application.
For more information see the generator output, ourexample application code andthe live example app.
To generate wrappers that are compatible withZurb Foundation 5, passthefoundation
option to the generator, like this:
rails generate simple_form:install --foundation
Please note that the Foundation wrapper does not support the:hint
option by default. In order toenable hints, please uncomment the appropriate line inconfig/initializers/simple_form_foundation.rb
.You will need to provide your own CSS styles for hints.
Please see theinstructions on how to install Foundation in a Rails app.
If you want to use the country select, you will need thecountry_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 thecountry inputs to something else, with a line like this in yoursimple_form.rb
initializer:
config.input_mappings={/country/=>:string}
Simple Form was designed to be customized as you need to. Basically it's a stack of components thatare invoked to create a complete html input for you, which by default contains label, hints, errorsand the input itself. It does not aim to create a lot of different logic from the default Railsform helpers, as they do a great job by themselves. Instead,Simple Form acts as a DSL and justmaps your input type (retrieved from the column definition in the database) to a specific helper method.
To start usingSimple Form you just have to use the helper it provides:
<%= simple_form_for @user do |f|%><%= f.input :username%><%= f.input :password%><%= f.button :submit%><% end%>
This will generate an entire form with labels for user name and password as well, and render errorsby 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. You can also add a hint,an error, or even a placeholder. For boolean inputs, you can add an inline label as well:
<%= simple_form_for @user do |f|%><%= f.input :username, label: 'Your username please', error: 'Username is mandatory, please specify one'%><%= f.input :password, hint: 'No special characters.'%><%= f.input :email, placeholder: 'user@domain.com'%><%= f.input :remember_me, inline_label: 'Yes, remember me'%><%= f.button :submit%><% end%>
In some cases you may want to disable labels, hints or errors. Or you may want to configure the htmlof any of them:
<%= simple_form_for @user do |f|%><%= f.input :username, label_html: { class: 'my_class' }, hint_html: { class: 'hint_class' }%><%= f.input :password, hint: false, error_html: { id: 'password_error' }%><%= f.input :password_confirmation, label: false%><%= f.button :submit%><% end%>
It is also possible to pass any html attribute straight to the input, by using the:input_html
option, for instance:
<%= simple_form_for @user do |f|%><%= f.input :username, input_html: { class: 'special' }%><%= f.input :password, input_html: { maxlength: 20 }%><%= f.input :remember_me, input_html: { value: '1' }%><%= f.button :submit%><% end%>
If you want to pass the same options to all inputs in the form (for example, a default class),you can use the:defaults
option insimple_form_for
. Specific options ininput
call willoverwrite the defaults:
<%= simple_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f|%><%= f.input :username, input_html: { class: 'special' }%><%= f.input :password, input_html: { maxlength: 20 }%><%= f.input :remember_me, input_html: { value: '1' }%><%= f.button :submit%><% end%>
SinceSimple Form generates a wrapper div around your label and input by default, you can passany html attribute to that wrapper as well using the:wrapper_html
option, like so:
<%= simple_form_for @user do |f|%><%= f.input :username, wrapper_html: { class: 'username' }%><%= f.input :password, wrapper_html: { id: 'password' }%><%= f.input :remember_me, wrapper_html: { class: 'options' }%><%= f.button :submit%><% end%>
Required fields are marked with an * prepended to their labels.
By default all inputs are required. When the form object includesActiveModel::Validations
(which, for example, happens with Active Record models), fields are required only when there ispresence
validation.Otherwise,Simple Form will mark fields as optional. For performance reasons, thisdetection is skipped on validations that make use of conditional options, such as:if
and:unless
.
And of course, therequired
property of any input can be overwritten as needed:
<%= simple_form_for @user do |f|%><%= f.input :name, required: false%><%= f.input :username%><%= f.input :password%><%= f.button :submit%><% end%>
By default,Simple Form will look at the column type in the database and use anappropriate input for the column. For example, a column created with type:text
in the database will use atextarea
input by default. See the sectionAvailable input types and defaults for each columntypefor a complete list of defaults.
Simple Form also lets you overwrite the default input type it creates:
<%= simple_form_for @user do |f|%><%= f.input :username%><%= f.input :password%><%= f.input :description, as: :text%><%= f.input :accepts, as: :radio_buttons%><%= f.button :submit%><% end%>
So instead of a checkbox for theaccepts attribute, you'll have a pair of radio buttons with yes/nolabels and a textarea instead of a text field for the description. You can also render booleanattributes usingas: :select
to show a dropdown.
It is also possible to give the:disabled
option toSimple Form, and it'll automatically markthe wrapper as disabled with a CSS class, so you can style labels, hints and other components insidethe wrapper as well:
<%= simple_form_for @user do |f|%><%= f.input :username, disabled: true, hint: 'You cannot change your username.'%><%= f.button :submit%><% end%>
Simple Form inputs accept the same options as their corresponding input type helper in Rails:
<%= simple_form_for @user do |f|%><%= f.input :date_of_birth, as: :date, start_year: Date.today.year - 90, end_year: Date.today.year - 12, discard_day: true, order: [:month, :year]%><%= f.input :accepts, as: :boolean, checked_value: 'positive', unchecked_value: 'negative'%><%= f.button :submit%><% end%>
By default,Simple Form generates a hidden field to handle the un-checked case for boolean fields.Passingunchecked_value: false
in the options for boolean fields will cause this hidden field to be omitted,following the convention in Rails. You can also specifyinclude_hidden: false
to skip the hidden field:
<%= simple_form_for @user do |f|%><%= f.input :just_the_checked_case, as: :boolean, include_hidden: false%><%= f.button :submit%><% end%>
Simple Form also allows you to use label, hint, input_field, error and full_error helpers(please take a look at the rdocs for each method for more info):
<%= simple_form_for @user do |f|%><%= f.label :username%><%= f.input_field :username%><%= f.hint 'No special characters, please!'%><%= f.error :username, id: 'user_name_error'%><%= f.full_error :token%><%= f.submit 'Save'%><% end%>
Any extra option passed to these methods will be rendered as html option.
Simple Form also allows you to strip away all the div wrappers around the<input>
field that isgenerated with the usualf.input
.The easiest way to achieve this is to usef.input_field
.
Example:
simple_form_for@userdo |f|f.input_field:namef.input_field:remember_me,as::booleanend
<form> ...<inputclass="string required"id="user_name"maxlength="255"name="user[name]"size="255"type="text"><inputname="user[remember_me]"type="hidden"value="0"><labelclass="checkbox"><inputclass="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 changingboolean_style
from default value:nested
to:inline
.
Example:
simple_form_for@userdo |f|f.input_field:namef.input_field:remember_me,as::boolean,boolean_style::inlineend
<form> ...<inputclass="string required"id="user_name"maxlength="255"name="user[name]"size="255"type="text"><inputname="user[remember_me]"type="hidden"value="0"><inputclass="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
And what if you want to create a select containing the age from 18 to 60 in your form? You can do itoverriding 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 berendered by default, so we don't need to pass theas: :select
option. Other types of collectionare:radio_buttons
and:check_boxes
. Those are added bySimple Form to Rails set of formhelpers (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 thisinstead 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 acceptlambda/procs in case you want to calculate the value or label in a special way eg. customtranslation. You can also define ato_label
method on your model asSimple Form will search forand 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 passprompt
andselected
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 htmloptgroup 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 beused to retrieve label/value attributes for theoption
tags. Besides that, you can give:
group_method => the method to be called on the given collection to generate the options foreach group (required)
group_label_method => the label method to be applied on the given collection to retrieve the labelfor theoptgroup (Simple Form will attempt to guess the best one the same way it does with
:label_method
)
Simple Form also supports:time_zone
and:country
. When using such helpers, you can give:priority
as an 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 on the site through theSimpleForm.country_priority
andSimpleForm.time_zone_priority
helpers.
Note: While usingcountry_select
if you want to restrict to only a subset of countries for a specificdrop down then you may use the:collection
option:
f.input:shipping_country,priority:["Brazil"],collection:["Australia","Brazil","New Zealand"]
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 andhas_and_belongs_to_many
roles. The structure would be something like:
classUser <ActiveRecord::Basebelongs_to:companyhas_and_belongs_to_many:rolesendclassCompany <ActiveRecord::Basehas_many:usersendclassRole <ActiveRecord::Basehas_and_belongs_to_many:usersend
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 radiobuttons and checkboxes as well:
f.association:company,as::radio_buttonsf.association:roles,as::check_boxes
The association helper just invokesinput
under the hood, so all options available to:select
,:radio_buttons
and:check_boxes
are also available to association. Additionally, you can specifythe 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 currentlydoes not work well with Mongoid and depending on the ORM you're using your mileage may vary.
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%>
Say you wanted to use a rails form helper but still wrap it inSimple Form goodness? You can, bycalling 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 ahash of additional attributes for each option.
Simple Form also comes with some extra helpers you can use inside rails default forms without relyingonsimple_form_for
helper. They are listed below.
Wrapper to useSimple Form inside a default rails form. It works in the same way that thefields_for
Rails helper, but change the builder to use theSimpleForm::FormBuilder
.
form_for@userdo |f|f.simple_fields_for:postsdo |posts_form|# Here you have all simple_form methods availableposts_form.input:titleendend
Creates a collection of radio inputs with labels associated (same API ascollection_select
):
form_for@userdo |f|f.collection_radio_buttons:options,[[true,'Yes'],[false,'No']],:first,:lastend
<inputid="user_options_true"name="user[options]"type="radio"value="true"/><labelclass="collection_radio_buttons"for="user_options_true">Yes</label><inputid="user_options_false"name="user[options]"type="radio"value="false"/><labelclass="collection_radio_buttons"for="user_options_false">No</label>
Creates a collection of checkboxes with labels associated (same API ascollection_select
):
form_for@userdo |f|f.collection_check_boxes:options,[[true,'Yes'],[false,'No']],:first,:lastend
<inputname="user[options][]"type="hidden"value=""/><inputid="user_options_true"name="user[options][]"type="checkbox"value="true"/><labelclass="collection_check_box"for="user_options_true">Yes</label><inputname="user[options][]"type="hidden"value=""/><inputid="user_options_false"name="user[options][]"type="checkbox"value="false"/><labelclass="collection_check_box"for="user_options_false">No</label>
To use this with associations in your model, you can do the following:
form_for@userdo |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 theitem_label_class
option:
f.collection_check_boxes:role_ids,Role.all,:id,:name,item_label_class:'my-custom-class'
The following table shows the html element you will get for each attributeaccording to its database definition. These defaults can be changed byspecifying the helper method in the columnMapping
as theas:
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 withname =~ /email/ |
url | input[type=url] | string withname =~ /url/ |
tel | input[type=tel] | string withname =~ /phone/ |
password | input[type=password] | string withname =~ /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 ofinput[type=radio] | belongs_to associations |
check_boxes | collection ofinput[type=checkbox] | has_many /has_and_belongs_to_many associations |
country | select (countries as options) | string withname =~ /country/ |
time_zone | select (timezones as options) | string withname =~ /time_zone/ |
It is very easy to add custom inputs toSimple Form. For instance, if you want to add a custom inputthat extends the string one, you just need to add this file:
# app/inputs/currency_input.rbclassCurrencyInput <SimpleForm::Inputs::Basedefinput(wrapper_options)merged_input_options=merge_wrapper_options(input_html_options,wrapper_options)"$#{@builder.text_field(attribute_name,merged_input_options)}".html_safeendend
And use it in your views:
f.input:money,as::currency
Note, you may have to create theapp/inputs/
directory and restart your webserver.
You can also redefine existingSimple Form inputs by creating a new class with the same name. Forinstance, if you want to wrap date/time/datetime in a div, you can do:
# app/inputs/date_time_input.rbclassDateTimeInput <SimpleForm::Inputs::DateTimeInputdefinput(wrapper_options)template.content_tag(:div,super)endend
Or if you want to add a class to all the select fields you can do:
# app/inputs/collection_select_input.rbclassCollectionSelectInput <SimpleForm::Inputs::CollectionSelectInputdefinput_html_classessuper.push('chosen')endend
If needed, you can namespace your custom inputs in a module and tellSimple Form to look fortheir definitions in this module. This can avoid conflicts with other form libraries (like Formtastic) that look upthe global context to find inputs definition too.
# app/inputs/custom_inputs/numeric_inputmoduleCustomInputsclassNumericInput <SimpleForm::Inputs::NumericInputdefinput_html_classessuper.push('no-spinner')endendend
And in theSimpleForm initializer :
# config/simple_form.rbconfig.custom_inputs_namespaces <<"CustomInputs"
You can create a custom form builder that usesSimple Form.
Create a helper method that callssimple_form_for
with a custom builder:
defcustom_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 fromSimpleForm::FormBuilder
.
classCustomFormBuilder <SimpleForm::FormBuilderdefinput(attribute_name,options={}, &block)super(attribute_name,options.merge(label:false), &block)endend
Simple Form uses all power of I18n API to lookup labels, hints, prompts and placeholders. To customize yourforms 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.'placeholders:user:username:'Your username'password:'****'include_blanks:user:age:'Rather not say'prompts:user:role:'Select your role'
And your forms will use this information to render the components for you.
Simple Form also lets you be more specific, separating lookups through actions.Let's say you want a different label for new and edit actions, the locale file wouldbe something like:
en:simple_form:labels:user:username:'User name'password:'Password'edit:username:'Change user name'password:'Change password'
This waySimple Form will figure out the right translation for you, based on the action beingrendered. And to be a little bit DRYer with your locale file, you can specify defaults for allmodels under the 'defaults' key:
en:simple_form:labels:defaults:username:'User name'password:'Password'new:username:'Choose a user name'hints:defaults:username:'User name to sign in.'password:'No special characters, please.'placeholders:defaults:username:'Your username'password:'****'
Simple Form will always look for a default attribute translation under the "defaults" key if nospecific is found inside the model key.
In addition,Simple Form will fallback to defaulthuman_attribute_name
from Rails when no othertranslation is found for labels. Finally, you can also overwrite any label, hint or placeholderinside your view, just by passing the option manually. This way the I18n lookup will be skipped.
For:prompt
and:include_blank
the I18n lookup is optional and to enable it is necessary to pass:translate
as value.
f.input:role,prompt::translate
Simple Form also has support for translating options in collection helpers. For instance, given aUser with a:role
attribute, you might want to create a select box showing translated labelsthat would post either:admin
or:editor
as value. WithSimple Form you could create an inputlike this:
f.input:role,collection:[:admin,:editor]
AndSimple Form will try a lookup like this in your locale file, to find the right labels to show:
en:simple_form:options:user:role:admin:'Administrator'editor:'Editor'
You can also use thedefaults
key as you would do with labels, hints and placeholders. It isimportant to notice thatSimple Form will only do the lookup for options if you give a collectioncomposed of symbols only. This is to avoid constant lookups to I18n.
It's also possible to translate buttons, using Rails' built-in I18n support:
en:helpers:submit:user:create:"Add %{model}"update:"Save Changes"
There are other options that can be configured through I18n API, such as required text and boolean.Be sure to check our locale file or the one copied to your application after you runrails generate simple_form:install
.
It should be noted that translations for labels, hints and placeholders for a namespaced model, e.g.Admin::User
, should be placed underadmin_user
, not underadmin/user
. This is different fromhow translations for namespaced model and attribute names are defined:
en:activerecord:models:admin/user:Userattributes:admin/user:name:Name
They should be placed underadmin/user
. Form labels, hints and placeholders for those attributes,though, should be placed underadmin_user
:
en:simple_form:labels:admin_user:name:Name
This difference exists becauseSimple Form relies onobject_name
provided by Rails'FormBuilder to determine the translation path for a given object instead ofi18n_key
from theobject itself. Thus, similarly, if a form for anAdmin::User
object is defined by callingsimple_form_for @admin_user, as: :some_user
,Simple Form will look for translationsundersome_user
instead ofadmin_user
.
When translatingsimple_fields_for
attributes be sure to use the same name you pass to it, e.g.simple_fields_for :posts
should be placed underposts
notpost
:
en:simple_form:labels:posts:title:'Post title'hints:posts:title:'A good title'placeholders:posts:title:'Once upon a time...'
Simple Form has several configuration options. You can read and change them in the initializercreated bySimple Form, so if you haven't executed the command below yet, please do:
rails generate simple_form:install
WithSimple Form you can configure how your components will be rendered using the wrappers API.The syntax looks like this:
config.wrapperstag::div,class::input,error_class::field_with_errors,valid_class::field_without_errorsdo |b|# Form extensionsb.use:html5b.optional:patternb.use:maxlengthb.use:placeholderb.use:readonly# Form componentsb.use:label_inputb.use:hint,wrap_with:{tag::span,class::hint}b.use:error,wrap_with:{tag::span,class::error}end
TheForm 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
TheForm extensions are used to generate some attributes or perform some lookups on the model toadd extra information to your components.
You can create newForm components using the wrappers API as in the following example:
config.wrappersdo |b|b.use:placeholderb.use:label_inputb.wrappertag::div,class:'separator'do |component|component.use:hint,wrap_with:{tag::span,class::hint}component.use:error,wrap_with:{tag::span,class::error}endend
this will wrap the hint and error components within adiv
tag using the class'separator'
.
You can customizeForm components passing options to them:
config.wrappersdo |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 customForm components on demand you can give it a name like this:
config.wrappersdo |b|b.use:placeholderb.use:label_inputb.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}endend
and now you can pass options to yourinput
calls to customize the:my_wrapper
Form component.
# Completely turns off the custom wrapperf.input:name,my_wrapper:false# Configure the htmlf.input:name,my_wrapper_html:{id:'special_id'}# Configure the tagf.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:smalldo |b|b.use:placeholderb.use:label_inputend
and use it in this way:
# Specifying to whole formsimple_form_for@user,wrapper::smalldo |f|f.input:nameend# Specifying to one inputsimple_form_for@userdo |f|f.input:name,wrapper::smallend
Simple Form also allows you to use optional elements. For instance, let's suppose you want to usehints or placeholders, but you don't want them to be generated automatically. You can set theirdefault values tofalse
or use theoptional
method. Is preferable to use theoptional
syntax:
config.wrappersplaceholder:falsedo |b|b.use:placeholderb.use:label_inputb.wrappertag::div,class:'separator'do |component|component.optional:hint,wrap_with:{tag::span,class::hint}component.use:error,wrap_with:{tag::span,class::error}endend
By setting it asoptional
, a hint will only be generated whenhint: 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 onlywhen the content is present.
b.wrappertag::span,class:'hint',unless_blank:truedo |component|component.optional:hintend
When you use custom wrappers, you might also be looking for a way to add custom components to yourwrapper. 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|%><divclass="row"><divclass="span1 number"> 1</div><divclass="span8"><%=f.input:title%></div></div><divclass="row"><divclass="span1 number"> 2</div><divclass="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 componentswill be:
# config/initializers/simple_form.rbDir[Rails.root.join('lib/components/**/*.rb')].each{ |f|requiref}
Create a new component within the path specified above:
# lib/components/numbers_component.rbmoduleNumbersComponent# To avoid deprecation warning, you need to make the wrapper_options explicit# even when they won't be used.defnumber(wrapper_options=nil)@number ||=beginoptions[:number].to_s.html_safeifoptions[:number].present?endendendSimpleForm.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:html5b.use:number,wrap_with:{tag:'div',class:'span1 number'}b.wrappertag:'div',class:'span8'do |ba|ba.use:placeholderba.use:labelba.use:inputba.use:error,wrap_with:{tag:'span',class:'help-inline'}ba.use:hint,wrap_with:{tag:'p',class:'help-block'}endend
By default,Simple Form will generate input field types and attributes that are supported in HTML5,but are considered invalid HTML for older document types such as HTML4 or XHTML1.0. The HTML5extensions include the new field types such as email, number, search, url, tel, and the newattributes such as required, autofocus, maxlength, min, max, step.
Most browsers will not care, but some of the newer ones - in particular Chrome 10+ - use therequired attribute to force a value into an input and will prevent form submission without it.Depending on the design of the application this may or may not be desired. In many cases it canbreak existing UI's.
It is possible to disable all HTML 5 extensions inSimple Form by removing thehtml5
component from the wrapper used to render the inputs.
For example, change:
config.wrapperstag::divdo |b|b.use:html5b.use:label_inputend
To:
config.wrapperstag::divdo |b|b.use:label_inputend
If you want to have all other HTML 5 features, such as the new field types, you can disable onlythe browser validation:
SimpleForm.browser_validations=false# default is true
This option adds a newnovalidate
property to the form, instructing it to skip all HTML 5validation. The inputs will still be generated with the required and other attributes, that mighthelp you to use some generic javascript validation.
You can also addnovalidate
to a specific form by setting the option on the form itself:
<%= simple_form_for(resource, html: { novalidate: true }) do |form|%>
Please notice that none of the configurations above will disable theplaceholder
component,which is an HTML 5 feature. We believe most of the newest browsers are handling this attributejust fine, and if they aren't, any plugin you use would take care of applying the placeholder.In any case, you can disable it if you really want to, by removing the placeholder componentfrom the components list in theSimple Form configuration file.
HTML 5 date / time inputs are not generated bySimple Form by default, so usingdate
,time
ordatetime
will all generate select boxes using normal Rails helpers. We believebrowsers are not totally ready for these yet, but you can easily opt-in on a per-input basisby passing the html5 option:
<%= f.input :expires_at, as: :date, html5: true%>
There are few ways to build forms with objects that don't inherit from Active Record, asfollows:
You can include the moduleActiveModel::Model
.
classUserincludeActiveModel::Modelattr_accessor:id,:nameend
If you are using Presenters or Decorators that inherit fromSimpleDelegator
you can delegateit to the model.
classUserPresenter <SimpleDelegator# Without that, Simple Form will consider the user model as the object.defto_modelselfendend
You can define all methods required by the helpers.
classUserextendActiveModel::Namingattr_accessor:id,:namedefto_modelselfenddefto_keyidenddefpersisted?falseendend
If your object doesn't implement those methods, you must make explicit it when you arebuilding the form
classUserattr_accessor:id,:name# The only method required to use the f.submit helper.defpersisted?falseendend
<%= simple_form_for(@user, as: :user, method: :post, url: users_path) do |f|%><%= f.input :name%><%= f.submit 'New user'%><% end%>
You can view theSimple Form documentation in RDoc format here:
http://rubydoc.info/github/heartcombo/simple_form/main/frames
We intend to maintain support for all Ruby / Rails versions that haven't reached end-of-life.
For more information about specific versions please checkRubyandRails maintenance policies, and our test matrix.
If you discover any bugs, feel free to create an issue on GitHub. Please add as much information aspossible to help us in fixing the potential bug. We also encourage you to help even more by forking andsending 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 toheartcombo@googlegroups.com.
- Carlos Antonio da Silva (https://github.com/carlosantoniodasilva)
- Rafael Mendonça França (https://github.com/rafaelfranca)
- Felipe Renan (https://github.com/feliperenan)
MIT License. Copyright 2020-2023 Rafael França, Carlos Antônio da Silva. Copyright 2009-2019 Plataformatec.
The Simple Form logo is licensed underCreative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
About
Forms made easy for Rails! It's tied to a simple DSL, with no opinion on markup.
Resources
License
Stars
Watchers
Forks
Packages0
Languages
- Ruby99.7%
- Other0.3%