Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/bootstrap-ruby/bootstrap_form

Official repository of the bootstrap_form gem, a Rails form builder that makes it super easy to create beautiful-looking forms using Bootstrap 5.
https://github.com/bootstrap-ruby/bootstrap_form

bootstrap rails rails-form-builder ruby

Last synced: 3 days ago
JSON representation

Official repository of the bootstrap_form gem, a Rails form builder that makes it super easy to create beautiful-looking forms using Bootstrap 5.

Awesome Lists containing this project

README

        

# bootstrap_form

[![Ruby](https://github.com/bootstrap-ruby/bootstrap_form/actions/workflows/ruby.yml/badge.svg)](https://github.com/bootstrap-ruby/bootstrap_form/actions/workflows/ruby.yml)
[![Gem Version](https://badge.fury.io/rb/bootstrap_form.svg)](https://rubygems.org/gems/bootstrap_form)

`bootstrap_form` is a Rails form builder that makes it super easy to integrate Bootstrap v5-style forms into your Rails application. It provides form helpers that augment the Rails form helpers. `bootstrap_forms`'s form helpers generate the form field and its label and all the Bootstrap mark-up required for proper Bootstrap display. `bootstrap_form` also provides:

* [Validation error messages](#validation-and-errors) below the field they correspond to, by default. You can also put the error messages after the label, or turn off `bootstrap_form`'s validation error handling and do it yourself. _Note that this applies to Rails-generated validation messages._ HTML 5 client-side validation and Rails validation out of the box don't really work well together. One discussion of the challenges and some solutions is [here](https://www.jorgemanrubia.com/2019/02/16/form-validations-with-html5-and-modern-rails/)
* Automatic [mark-up for the `required` attribute](#required-fields) on required fields.
* An easy way to consistently show [help](#help-text) text on fields.
* Mark-up for [Bootstrap horizontal forms](#horizontal-forms) (labels to the left of their fields, like a traditional desktop application), if that's what you want.
* Many [options](#form-helpers) to modify or augment the generated mark-up.
* A way to [escape to the Rails form helpers](#accessing-rails-form-helpers) if you need to do something that `bootstrap_form` can't do.

Some other nice things that `bootstrap_form` does for you are:

* Reduces the amount of code in your `.erb` files.
* Gets you going faster with Bootstrap, because you don't need to learn all the rules of Bootstrap form mark-up to get started.
* Reduces errors, because you're doing less typing.
* Makes it easier to see the logic of the form, because it's not mixed in with the Bootstrap mark-up.

`bootstrap_form` works like the standard Rails form helpers, and this README assumes you know how they work. You start a form with one of [`bootstrap_form_with`](#bootstrap_form_with), [`bootstrap_form_for`](#bootstrap_form_for), or [`bootstrap_form_tag`](#bootstrap_form_tag) in a view file. You get a form builder that calls the [`bootstrap_form` helpers](#form-helpers) instead of the standard Rails helpers. You use that form builder in the view file to render one or more form fields.

## Requirements

`bootstrap_form` supports at a minimum the currently supported versions of Ruby and Rails:

* Ruby 3.0+ (https://www.ruby-lang.org/en/downloads/branches/)
* Rails 6.1+ (https://guides.rubyonrails.org/maintenance_policy.html)
* Bootstrap 5.0+

## Installation

Install Bootstrap 5. There are many ways to do this, depending on the asset pipeline you're using in your Rails application. One way is to use the gem that works with Sprockets. To do so, in a brand new Rails 7.0+ application created _without_ the `--webpacker` option, add the `bootstrap` gem to your `Gemfile`:

```ruby
gem "bootstrap", "~> 5.0"
```

And follow the remaining instructions in the [official bootstrap installation guide](https://github.com/twbs/bootstrap-rubygem#a-ruby-on-rails) for setting up `application.scss` and `application.js`.

Add the `bootstrap_form` gem to your `Gemfile`:

```ruby
gem "bootstrap_form", "~> 5.4"
```

Then:

`bundle install`

Depending on which CSS pre-processor you are using, adding the bootstrap form styles differs slightly.
If you use Rails in the default mode without any pre-processor, you'll have to add the following line to your `application.css` file:

```css
*= require rails_bootstrap_forms
```

If you followed the [official bootstrap installation guide](https://github.com/twbs/bootstrap-rubygem#a-ruby-on-rails), you'll probably have switched to SCSS. In this case add the following line to your `application.scss`:

```scss
@import "rails_bootstrap_forms.css";
```

## Usage

### bootstrap_form_for

To get started, use the `bootstrap_form_for` helper in place of the Rails `form_for` helper. Here's an example:

![Example 0](demo/doc/screenshots/bootstrap/readme/00_example.png "Example 0")
```erb
<%= bootstrap_form_for(@user) do |f| %>
<%= f.email_field :email %>
<%= f.password_field :password %>
<%= f.check_box :remember_me %>
<%= f.submit "Log In" %>
<% end %>
```

This generates the following HTML:

```html


Email



Password





Remember me

```

### bootstrap_form_tag

If your form is not backed by a model, use the `bootstrap_form_tag`. Usage of this helper is the same as `bootstrap_form_for`, except no model object is passed in as the first argument. Here's an example:

![Example 1](demo/doc/screenshots/bootstrap/readme/01_example.png "Example 1")
```erb
<%= bootstrap_form_tag url: '/subscribe' do |f| %>
<%= f.email_field :email, value: '[email protected]' %>
<%= f.submit %>
<% end %>
```

This generates:

```html


Email


```

### bootstrap_form_with

To get started, just use the `bootstrap_form_with` helper in place of `form_with`. Here's an example:

![Example 2](demo/doc/screenshots/bootstrap/readme/02_example.png "Example 2")
```erb
<%= bootstrap_form_with(model: @user, local: true) do |f| %>
<%= f.email_field :email %>
<%= f.password_field :password, help: 'A good password should be at least six characters long' %>
<%= f.check_box :remember_me %>
<%= f.submit "Log In" %>
<% end %>
```

This generates:

```html


Email



Password

A good password should be at least six characters long




Remember me

```

`bootstrap_form_with` supports both the `model:` and `url:` use cases
in `form_with`.

`form_with` has some important differences compared to `form_for` and `form_tag`, and these differences apply to `bootstrap_form_with`. A good summary of the differences can be found at: https://m.patrikonrails.com/rails-5-1s-form-with-vs-old-form-helpers-3a5f72a8c78a, or in the [Rails documentation](api.rubyonrails.org).

### bootstrap_fields_for and bootstrap_fields

Adding fields for a different object without nesting can be achieved using the `bootstrap_fields_for` and
`bootstrap_fields` helpers in the same way it is done in Rails.

![Example 3](demo/doc/screenshots/bootstrap/readme/03_example.png "Example 3")
```erb
<%= bootstrap_form_with model: @user do |f| %>
<%= f.email_field :email %>
<%= bootstrap_fields_for :parent do |pf| %>
<%= pf.email_field :email, label: 'Parent email' %>
<% end %>
<%= bootstrap_fields @user.address do |af| %>
<%= af.text_field :street_name %>
<% end %>
<%= f.primary "Save" %>
<% end %>
```

Generated HTML:

```html


Email



Parent email



Street name


```

## Configuration

`bootstrap_form` can be used out-of-the-box without any configuration. However, `bootstrap_form` does have an optional configuration file at `config/initializers/bootstrap_form.rb` for setting options that affect all generated forms in an application.

The current configuration options are:

| Option | Default value | Description |
|---------------------------|------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `default_form_attributes` | | `bootstrap_form` versions 3 and 4 added a role="form" attribute to all forms. The W3C validator will raise a **warning** on forms with a role="form" attribute. `bootstrap_form` version 5 drops this attribute by default. Set this option to `{ role: "form" }` to make forms non-compliant with W3C, but generate the `role="form"` attribute like `bootstrap_form` versions 3 and 4. |

Example:

```ruby
# config/initializers/bootstrap_form.rb
BootstrapForm.configure do |c|
c.default_form_attributes = { role: "form" } # to make forms non-compliant with W3C.
end
```

## Form Helpers

`bootstrap_form` provides its own version of the following Rails form helpers:

```
button email_field search_field
check_box file_field select
collection_check_boxes grouped_collection_select submit
collection_radio_buttons hidden_field (not wrapped, but supported) telephone_field
collection_select month_field text_area
color_field number_field text_field
date_field password_field time_field
date_select phone_field time_select
datetime_field radio_button time_zone_select
datetime_local_field range_field url_field
datetime_select rich_text_area week_field
```

By default, the helpers generate a `label` tag, and an `input`, `select`, or `textarea` tag, by calling the Rails `label` helper, and then the Rails helper with the same name as the `bootstrap_form` helper.

The `bootstrap_form` helpers accept the same options as the standard Rails form helpers, and pass those options through to the Rails helper. They also accept additional options, described in the following section.

## Form Helper Options

Many of the helpers accept the same options. The exceptions are:

[button](#submit-buttons),
[check_box](#checkboxes-and-radios),
[collection_check_boxes](#collections),
[collection_radio_buttons](#collections),
[collection_select](#selects),
[date_select](#date-helpers),
[datetime_select](#date-helpers),
[file_field](#file-fields),
[grouped_collection_select](#selects),
[hidden_field](#hidden-fields),
[radio_button](#checkboxes-and-radios),
[rich_text_area](#rich-text-areas-aka-trix-editor),
[select](#selects),
[submit](#submit-buttons),
[time_select](#date-helpers),
[time_zone_select](#selects)

The options for the form helpers that aren't in the exceptions list are described in the following sub-sections:

### Labels

Use the `label` option if you want to specify the field's label text:

![Example 4](demo/doc/screenshots/bootstrap/readme/04_example.png "Example 4")
```erb
<%= f.password_field :password_confirmation, label: "Confirm Password" %>
```

This generates:

```html


Confirm Password


```

To hide a label, use the `hide_label: true` option. This adds the `visually-hidden`
class, which keeps your labels accessible to those using screen readers.

![Example 5](demo/doc/screenshots/bootstrap/readme/05_example.png "Example 5")
```erb
<%= f.text_area :comment, hide_label: true, placeholder: "Leave a comment..." %>
```

This generates:

```html


Comment


```

To add custom classes to the field's label:

![Example 6](demo/doc/screenshots/bootstrap/readme/06_example.png "Example 6")
```erb
<%= f.email_field :email, label_class: "custom-class" %>
```

This generates:

```html


Email


```

Or you can add the label as input placeholder instead (this automatically hides the label):

![Example 7](demo/doc/screenshots/bootstrap/readme/07_example.png "Example 7")
```erb
<%= f.email_field :email, value: '', label_as_placeholder: true %>
```

This generates:

```html


Email


```

### Input Elements / Controls

To specify the class of the generated input tag, use the `control_class` option:

![Example 8](demo/doc/screenshots/bootstrap/readme/08_example.png "Example 8")
```erb
<%= f.text_field :email, control_class: "custom-class" %>
```

This generates:

```html


Email


```

### Help Text

To add help text, use the `help` option:

![Example 9](demo/doc/screenshots/bootstrap/readme/09_example.png "Example 9")
```erb
<%= f.password_field :password, help: "Must be at least 6 characters long" %>
```

This generates:

```html


Password

Must be at least 6 characters long

```

This gem is also aware of help messages in locale translation files (i18n):

```yml
en:
activerecord:
help:
user:
password: "A good password should be at least six characters long"
```

Help translations containing HTML should follow the convention of appending `_html` to the name:

```yml
en:
activerecord:
help:
user:
password_html: "A good password should be at least six characters long"
```

If your model name has multiple words (like `SuperUser`), the key on the
translation file should be underscored (`super_user`).

You can override help translations for a particular field by passing the `help`
option or turn them off completely by passing `help: false`.

### Prepending and Appending Inputs

You can pass `prepend` and/or `append` options to input fields:

![Example 10](demo/doc/screenshots/bootstrap/readme/10_example.png "Example 10")
```erb
<%= f.text_field :price, prepend: "$", append: ".00" %>
```

This generates:

```html


Price

$

.00


```

If you want to attach multiple items to the input, pass them as an array:

![Example 11](demo/doc/screenshots/bootstrap/readme/11_example.png "Example 11")
```erb
<% icon = capture do %><% end %>
<%= f.text_field :price, prepend: ['Net', icon], append: ['.00', 'per day'] %>
```

This generates:

```html


Price

Net





.00
per day


```

You can also prepend and append buttons. Note: The buttons must contain the
`btn` class to generate the correct markup.

![Example 12](demo/doc/screenshots/bootstrap/readme/12_example.png "Example 12")
```erb
<%= f.text_field :search, append: link_to("Go", "#", class: "btn btn-secondary") %>
```

This generates:

```html


Search


Go


```

To add a class to the input group wrapper, use the `:input_group_class` option.

![Example 13](demo/doc/screenshots/bootstrap/readme/13_example.png "Example 13")
```erb
<%= f.email_field :email, append: f.primary('Subscribe'), input_group_class: 'input-group-lg' %>
```

This generates:

```html


Email





```

### Additional Form Group Attributes

Bootstrap mark-up dictates that most input field types have the label and input wrapped in a `div.mb-3`.

If you want to change the CSS class or any other attribute to the form group div, you can use the `wrapper: { class: 'mb-3 additional-class', data: { foo: 'bar' } }` option.

![Example 14](demo/doc/screenshots/bootstrap/readme/14_example.png "Example 14")
```erb
<%= f.text_field :name, wrapper: { class: 'mb-3 has-warning', data: { foo: 'bar' } } %>
```

This generates:

```html


Name


```

Which produces the following output:

![Example 15](demo/doc/screenshots/bootstrap/readme/15_example.png "Example 15")
```erb


Id


```

This generates:

```html


Id


```

If you only want to set the class on the form group div, you can use the `wrapper_class` option: `wrapper_class: 'mb-3 additional-class'`.
It's just a short form of `wrapper: { class: 'mb-3 additional-class' }`.

If you don't want any class on the form group div, you can set it to `false`: `wrapper_class: false`.

### Suppressing the Form Group Altogether

You may want to define your own form group div around a field. To do so, add the option `wrapper: false` to the input field. For example:

![Example 16](demo/doc/screenshots/bootstrap/readme/16_example.png "Example 16")
```erb
<%= f.form_group :user do %>
<%= f.email_field :email, wrapper: false %>
<% end %>
```

Generated HTML:

```html




```

Note that Bootstrap relies on the form group div to correctly format most fields, so if you use the `wrapper: false` option, you should provide your own form group div around the input field. You can write your own HTML, or use the `form_group` helper.

## Selects

Our select helper accepts the same arguments as the [default Rails helper](http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select). Here's an example of how you pass both options and html_options hashes:

![Example 17](demo/doc/screenshots/bootstrap/readme/17_example.png "Example 17")
```erb
<%= f.select :product, [["Apple", 1], ["Grape", 2]], { label: "Choose your favorite fruit:", wrapper: { class: 'has-warning', data: { foo: 'bar' } } }, { class: "selectpicker" } %>
```

This generates:

```html


Choose your favorite fruit:

Apple
Grape


```

## Checkboxes and Radios

Checkboxes and radios should be placed inside of a `form_group` to render
properly. The following example ensures that the entire form group will display
an error if an associated validations fails:

![Example 18](demo/doc/screenshots/bootstrap/readme/18_example.png "Example 18")
```erb
<%= f.form_group :skill_level, label: { text: "Skill" }, help: "Optional Help Text" do %>
<%= f.radio_button :skill_level, 0, label: "Novice", checked: true %>
<%= f.radio_button :skill_level, 1, label: "Intermediate" %>
<%= f.radio_button :skill_level, 2, label: "Advanced" %>
<% end %>

<%= f.form_group :terms do %>
<%= f.check_box :terms, label: "I agree to the Terms of Service" %>
<% end %>
```

This generates:

```html


Skill


Novice



Intermediate



Advanced

Optional Help Text





I agree to the Terms of Service


```

You can also create a checkbox using a block:

![Example 19](demo/doc/screenshots/bootstrap/readme/19_example.png "Example 19")
```erb
<%= f.form_group :terms, label: { text: "Optional Label" } do %>
<%= f.check_box :terms do %>
You need to check this box to accept our terms of service and privacy policy
<% end %>
<% end %>
```

This generates:

```html


Optional Label




You need to check this box to accept our terms of service and privacy policy



```

To display checkboxes and radios inline, pass the `inline: true` option:

![Example 20](demo/doc/screenshots/bootstrap/readme/20_example.png "Example 20")
```erb
<%= f.form_group :skill_level, label: { text: "Skill" } do %>
<%= f.radio_button :skill_level, 0, label: "Novice", inline: true %>
<%= f.radio_button :skill_level, 1, label: "Intermediate", inline: true %>
<%= f.radio_button :skill_level, 2, label: "Advanced", inline: true %>
<% end %>
```

This generates:

```html


Skill


Novice



Intermediate



Advanced


```

Check boxes and radio buttons are wrapped in a `div.form-check`. You can add classes to this `div` with the `:wrapper_class` option:

![Example 21](demo/doc/screenshots/bootstrap/readme/21_example.png "Example 21")
```erb
<%= f.radio_button :skill_level, 0, label: "Novice", inline: true, wrapper_class: "w-auto" %>
```

This generates:

```html



Novice

```

You can also add a style to the tag using the `wrapper` option:

![Example 22](demo/doc/screenshots/bootstrap/readme/22_example.png "Example 22")
```erb
<%= f.check_box :skilled, inline: true, wrapper: {style: "color: green"} %>
<%= f.radio_button :skill_level, 0, label: "Novice", inline: true, wrapper: {class: 'w-auto', style: "color: red"} %>
```

This generates:

```html




Skilled



Novice

```

### Switches

To render checkboxes as switches with Bootstrap 4.2+, use `switch: true`:

![Example 23](demo/doc/screenshots/bootstrap/readme/23_example.png "Example 23")
```erb
<%= f.check_box :remember_me, switch: true %>
```

This generates:

```html




Remember me

```

### Collections

`bootstrap_form` also provides helpers that automatically create the
`form_group` and the `radio_button`s or `check_box`es for you:

![Example 24](demo/doc/screenshots/bootstrap/readme/24_example.png "Example 24")
```erb
<%= f.collection_radio_buttons :skill_level, Skill.all, :id, :name %>
<%= f.collection_check_boxes :skills, Skill.all, :id, :name %>
```

This generates:

```html


Skill level


Mind reading



Farming


Skills


Mind reading



Farming


```

NOTE: These helpers do not currently support a block, unlike their equivalent Rails helpers. See issue [#477](https://github.com/bootstrap-ruby/bootstrap_form/issues/477). If you need to use the block syntax, use `collection_check_boxes_without_bootstrap` or `collection_radio_buttons_without_bootstrap` for now.

Collection methods accept these options:

* `:label`: Customize the `form_group`'s label
* `:hide_label`: Pass true to hide the `form_group`'s label
* `:help`: Add a help span to the `form_group`
* Other options will be forwarded to the `radio_button`/`check_box` method

To add `data-` attributes to a collection of radio buttons, map your models to an array and add a hash:

![Example 25](demo/doc/screenshots/bootstrap/readme/25_example.png "Example 25")
```erb
<%# Use the :first and :second elements of the array to be the value and label respectively %>
<%- choices = @collection.map { |addr| [ addr.id, addr.street, { 'data-zip-code': addr.zip_code } ] } -%>

<%= f.collection_radio_buttons :misc, choices, :first, :second %>
```

This generates:

```html


Misc


Foo



Bar


```

## Range Controls

You can create a range control like this:

![Example 26](demo/doc/screenshots/bootstrap/readme/26_example.png "Example 26")
```erb
<%= f.range_field :excellence %>
```

This generates:

```html


Excellence


```

## Static Controls

You can create a static control like this:

![Example 27](demo/doc/screenshots/bootstrap/readme/27_example.png "Example 27")
```erb
<%= f.static_control :email %>
```

This generates:

```html


Email


```

Here's the output for a horizontal layout:

![Example 28](demo/doc/screenshots/bootstrap/readme/28_example.png "Example 28")
```erb
<%= bootstrap_form_for(@user, layout: :horizontal) do |f| %>
<%= f.static_control :email %>
<% end %>
```

This generates:

```html


Email



```

You can also create a static control that isn't based on a model attribute:

![Example 29](demo/doc/screenshots/bootstrap/readme/29_example.png "Example 29")
```erb
<%= f.static_control :field_name, label: "Custom Static Control", value: "Content Here" %>
```

This generates:

```html


Custom Static Control


```

`field_name` may be any name that isn't already used in the form. Note that you may get "unpermitted parameter" messages in your log file with this approach.

You can also create the static control the following way, if you don't need to get the value of the static control as a parameter when the form is submitted:

![Example 30](demo/doc/screenshots/bootstrap/readme/30_example.png "Example 30")
```erb
<%= f.static_control label: "Custom Static Control", value: "Content Here", name: nil %>
```

This generates:

```html


Custom Static Control


```

(If you neither provide a field name nor `name: nil`, the Rails code that submits the form will give a JavaScript error.)

Prior to version 4 of `bootstrap_form`, you could pass a block to the `static_control` method.
The value of the block would be used for the content of the static "control".
Bootstrap 4 actually creates and styles a disabled input field for static controls, so the value of the control has to be specified by the `value:` option.
Passing a block to `static_control` no longer has any effect.

## Date Helpers

The multiple selects that the date and time helpers (`date_select`,
`time_select`, `datetime_select`) generate are wrapped inside a
`div.rails-bootstrap-forms-[date|time|datetime]-select` tag. This is because
Bootstrap automatically styles our controls as `block`s. This wrapper fixes
this by defining these selects as `inline-block` and a width of `auto`.

## Submit Buttons

The `btn btn-secondary` CSS classes are automatically added to your submit
buttons.

![Example 31](demo/doc/screenshots/bootstrap/readme/31_example.png "Example 31")
```erb
<%= f.submit %>
```

This generates:

```html

```

You can also use the `primary` helper, which adds `btn btn-primary` to your
submit button:

![Example 32](demo/doc/screenshots/bootstrap/readme/32_example.png "Example 32")
```erb
<%= f.primary "Optional Label" %>
```

This generates:

```html

```

You can specify your own classes like this:

![Example 33](demo/doc/screenshots/bootstrap/readme/33_example.png "Example 33")
```erb
<%= f.submit "Log In", class: "btn btn-success" %>
```

This generates:

```html

```

If the `primary` helper receives a `render_as_button: true` option or a block,
it will be rendered as an HTML button, instead of an input tag. This allows you
to specify HTML content and styling for your buttons (such as adding
illustrative icons to them). For example, the following statements

![Example 34](demo/doc/screenshots/bootstrap/readme/34_example.png "Example 34")
```erb
<%= f.primary "Save changes ".html_safe, render_as_button: true %>

<%= f.primary do
concat 'Save changes '
concat content_tag(:span, nil, class: 'bi bi-save')
end %>
```

This generates:

```html
Save changes

Save changes

```

are equivalent, and each of them both be rendered as:

```html
Save changes
```

If you wish to add additional CSS classes to your button, while keeping the
default ones, you can use the `extra_class` option. This is particularly useful
for adding extra details to buttons (without forcing you to repeat the
Bootstrap classes), or for element targeting via CSS classes.
Be aware, however, that using the `class` option will discard any extra classes
you add. As an example, the following button declarations

![Example 35](demo/doc/screenshots/bootstrap/readme/35_example.png "Example 35")
```erb
<%= f.primary "My Nice Button", extra_class: 'my-button' %>

<%= f.primary "My Button", class: 'my-button' %>
```

will be rendered as

```html

```

(some unimportant HTML attributes have been removed for simplicity)

## Rich Text Areas AKA Trix Editor

![Example 36](demo/doc/screenshots/bootstrap/readme/36_example.png "Example 36")
```erb
<%= f.rich_text_area(:life_story) %>
```

will be rendered as:

```html


Life story




Bold
Italic
Strikethrough
Link


Heading
Quote
Code
Bullets
Numbers
Decrease Level
Increase Level


Attach Files




Undo
Redo









```

## File Fields

The `file_field` helper generates mark-up for a Bootstrap 4 custom file field entry. It takes the [options for `text_field`](#form-helper-options), minus `append` and `prepend`.

## Hidden Fields

The `hidden_field` helper in `bootstrap_form` calls the Rails helper directly, and does no additional mark-up.

## Accessing Rails Form Helpers

If you want to use the original Rails form helpers for a particular field,
append `_without_bootstrap` to the helper:

![Example 37](demo/doc/screenshots/bootstrap/readme/37_example.png "Example 37")
```erb
<%= f.text_field_without_bootstrap :email %>
```

This generates:

```html

```

## Form Styles

By default, your forms will stack labels on top of controls and your controls
will grow to 100 percent of the available width. This is consistent with Bootstrap's "mobile first" approach.

### Inline Forms

To use an inline-layout form, use the `layout: :inline` option. To hide labels,
use the `hide_label: true` option, which keeps your labels accessible to those
using screen readers.

![Example 38](demo/doc/screenshots/bootstrap/readme/38_example.png "Example 38")
```erb
<%= bootstrap_form_for(@user, layout: :inline) do |f| %>
<%= f.email_field :email, hide_label: true %>
<%= f.password_field :password, hide_label: true %>
<%= f.check_box :remember_me %>
<%= f.submit %>
<% end %>
```

This generates:

```html


Email



Password






Remember me




```

To skip label rendering at all, use `skip_label: true` option.

![Example 39](demo/doc/screenshots/bootstrap/readme/39_example.png "Example 39")
```erb
<%= f.password_field :password, skip_label: true %>
```

This generates:

```html




```

### Horizontal Forms

To use a horizontal-layout form with labels to the left of the control, use the
`layout: :horizontal` option. You should specify both `label_col` and
`control_col` css classes as well (they default to `col-sm-2` and `col-sm-10`).

In the example below, the submit button has been wrapped in a `form_group` to
keep it properly aligned.

![Example 40](demo/doc/screenshots/bootstrap/readme/40_example.png "Example 40")
```erb
<%= bootstrap_form_for(@user, layout: :horizontal, label_col: "col-sm-2", control_col: "col-sm-10") do |f| %>
<%= f.email_field :email %>
<%= f.password_field :password %>
<%= f.check_box :remember_me %>
<%= f.form_group do %>
<%= f.submit %>
<% end %>
<% end %>
```

This generates:

```html


Email





Password









Remember me







```

The `label_col` and `control_col` css classes can also be changed per control:

![Example 41](demo/doc/screenshots/bootstrap/readme/41_example.png "Example 41")
```erb
<%= bootstrap_form_for(@user, layout: :horizontal) do |f| %>
<%= f.email_field :email %>
<%= f.text_field :age, label_col: %w[col-sm-3 text-bg-info], control_col: %w[col-sm-3 text-bg-success] %>
<%= f.check_box :terms, label_col: "", control_col: "col-sm-11" %>
<%= f.form_group do %>
<%= f.submit %>
<% end %>
<% end %>
```

This generates:

```html


Email





Age









Terms







```

or default value can be changed in initializer:

```ruby
# config/initializers/bootstrap_form.rb
module BootstrapForm
class FormBuilder
def default_label_col
'col-sm-4'
end
def default_control_col
'col-sm-8'
end
def default_layout
# :vertical, :horizontal or :inline
:horizontal
end
end
end
```

Control col wrapper class can be modified with `add_control_col_class`. This option will preserve column definition:

![Example 42](demo/doc/screenshots/bootstrap/readme/42_example.png "Example 42")
```erb
<%= bootstrap_form_for(@user, layout: :horizontal) do |f| %>
<%= f.email_field :email %>
<%= f.text_field :age, add_control_col_class: "additional-control-col-class" %>
<%= f.form_group do %>
<%= f.submit %>
<% end %>
<% end %>
```

This generates:

```html


Email





Age








```

### Custom Field Layout

The form-level `layout` can be overridden per field, unless the form-level layout was `inline`:

![Example 43](demo/doc/screenshots/bootstrap/readme/43_example.png "Example 43")
```erb
<%= bootstrap_form_for(@user, layout: :horizontal) do |f| %>
<%= f.email_field :email %>


<%= f.text_field :feet, layout: :vertical %>

<%= f.text_field :inches, layout: :vertical %>


<%= f.check_box :terms, layout: :vertical %>
<%= f.submit %>
<% end %>
```

This generates:

```html


Email







Feet





Inches








Terms


```

A form-level `layout: :inline` can't be overridden because of the way Bootstrap 4 implements in-line layouts. One possible work-around is to leave the form-level layout as default, and specify the individual fields as `layout: :inline`, except for the fields(s) that should be other than in-line.

### Floating Labels

The `floating` option can be used to enable Bootstrap 5's floating labels. This option is supported on text fields
and dropdowns. Here's an example:

![Example 44](demo/doc/screenshots/bootstrap/readme/44_example.png "Example 44")
```erb
<%= bootstrap_form_for(@user) do |f| %>
<%= f.email_field :email, floating: true %>
<%= f.password_field :password, floating: true %>
<%= f.password_field :password, floating: true %>
<%= f.select :status, [["Active", 1], ["Inactive", 2]], include_blank: "Select a value", floating: true %>
<%= f.submit "Log In" %>
<% end %>
```

This generates:

```html



Email



Password



Password



Select a value
Active
Inactive

Status

```

## Validation and Errors

Rails normally wraps fields with validation errors in a `div.field_with_errors`, but this behaviour isn't consistent with Bootstrap 4 styling. By default, `bootstrap_form` generations in-line errors which appear below the field. But it can also generate errors on the label, or not display any errors, leaving it up to you.

### Inline Errors

By default, fields that have validation errors will be outlined in red and the
error will be displayed below the field. Here's an example:

![Example 45](demo/doc/screenshots/bootstrap/readme/45_example.png "Example 45")
```erb
<%= bootstrap_form_for(@user_with_error) do |f| %>
<%= f.email_field :email %>
<%= f.collection_radio_buttons :misc, Skill.all, :id, :name %>
<%= f.collection_check_boxes :preferences, [[1, 'Good'], [2, 'Bad']], :first, :second %>
<%= f.fields_for :address do |af| %>
<%= af.text_field :street %>
<% end %>
<% end %>
```

Generated HTML:

```html


Email

is invalid



Misc


Mind reading



Farming
is invalid





Preferences


Good



Bad
is invalid




Street

is invalid

```

You can turn off inline errors for the entire form like this:

```erb
<%= bootstrap_form_for(@user_with_error, inline_errors: false) do |f| %>
...
<% end %>
```

### Label Errors

You can also display validation errors in the field's label; just turn
on the `:label_errors` option. Here's an example:

![Example 46](demo/doc/screenshots/bootstrap/readme/46_example.png "Example 46")
```erb
<%= bootstrap_form_for(@user_with_error, label_errors: true) do |f| %>
<%= f.email_field :email %>
<% end %>
```

Generated HTML:

```html


Email is invalid

```

By default, turning on `:label_errors` will also turn off
`:inline_errors`. If you want both turned on, you can do that too:

```erb
<%= bootstrap_form_for(@user, label_errors: true, inline_errors: true) do |f| %>
...
<% end %>
```

### Alert Messages

To display an error message with an error summary, you can use the
`alert_message` helper. This won't output anything unless a model validation
has failed.

![Example 47](demo/doc/screenshots/bootstrap/readme/47_example.png "Example 47")
```erb
<%= bootstrap_form_for @user_with_error do |f| %>
<%= f.alert_message "Please fix the errors below." %>
<% end %>
```

Which outputs:

```html


Please fix the errors below.



  • Email is invalid

  • Misc is invalid

  • Preferences is invalid


```

You can turn off the error summary like this:

![Example 48](demo/doc/screenshots/bootstrap/readme/48_example.png "Example 48")
```erb
<%= bootstrap_form_for @user_with_error do |f| %>
<%= f.alert_message "Please fix the errors below.", error_summary: false %>
<% end %>
```

This generates:

```html

Please fix the errors below.

```

To output a simple unordered list of errors, use the `error_summary` helper.

![Example 49](demo/doc/screenshots/bootstrap/readme/49_example.png "Example 49")
```erb
<%= bootstrap_form_for @user_with_error do |f| %>
<%= f.error_summary %>
<% end %>
```

Which outputs:

```html


  • Email is invalid

  • Misc is invalid

  • Preferences is invalid

```

### Errors On

If you want to display a custom inline error for a specific attribute not represented by a form field, use the `errors_on` helper.

![Example 50](demo/doc/screenshots/bootstrap/readme/50_example.png "Example 50")
```erb
<%= bootstrap_form_for @user_with_error do |f| %>

<%= f.errors_on :email %>
<% end %>
```

Which outputs:

```html


Email is invalid

```

Note that the `invalid-feedback` `div` is hidden unless there is a preceding element under the same parent that has class `is-invalid`. For the examples, we've artificially added a hidden input.

You can hide the attribute name like this:

![Example 51](demo/doc/screenshots/bootstrap/readme/51_example.png "Example 51")
```erb
<%= bootstrap_form_for @user_with_error do |f| %>

<%= f.errors_on :email, hide_attribute_name: true %>
<% end %>
```

Which outputs:

```html


is invalid

```

You can also use a custom class for the wrapping div, like this:

![Example 52](demo/doc/screenshots/bootstrap/readme/52_example.png "Example 52")
```erb
<%= bootstrap_form_for @user_with_error do |f| %>

<%= f.errors_on :email, custom_class: 'custom-error' %>
<% end %>
```

Which outputs:

```html


Email is invalid

```

Note that adding the custom class removes the default `invalid-feedback` class. If you still want the default `invalid-feedback` formatting, add it to your `custom_class`es.

## Required Fields

A label that is associated with a required field is automatically annotated with
a `required` CSS class. `bootstrap_form` doesn't provide any styling for required fields. You're free to add any appropriate CSS to style
required fields as desired. One example would be to automatically add an
asterisk to the end of the label:

```css
label.required:after {
content:" *";
}
```

The label `required` class is determined based on the definition of a presence
validator with the associated model attribute. Presently this is one of:
ActiveRecord::Validations::PresenceValidator or
ActiveModel::Validations::PresenceValidator.

In cases where this behaviour is undesirable, use the `required` option to force the class to be present or absent:

![Example 53](demo/doc/screenshots/bootstrap/readme/53_example.png "Example 53")
```erb
<%= f.password_field :login, label: "New Username", required: true %>
<%= f.password_field :password, label: "New Password", required: false %>
```

This generates:

```html


New Username



New Password


```

### Required belongs_to associations

Adding a form control for a `belongs_to` field will automatically pick up the associated presence validator.

![Example 54](demo/doc/screenshots/bootstrap/readme/54_example.png "Example 54")
```erb
<%= bootstrap_form_for(@address, url: '/address') do |f| %>
<%= f.collection_select :user_id, @users, :id, :email, include_blank: "Select a value" %>
<%= f.text_field :street %>
<%= f.text_field :city %>
<%= f.text_field :state %>
<%= f.text_field :zip_code %>
<%= f.submit "Save" %>
<% end %>
```

Generated HTML:

```html


User

Select a value
[email protected]



Street



City



State



Zip code


```

## Disabled fields

Fields can be disabled using the standard Rails form helper option.

![Example 55](demo/doc/screenshots/bootstrap/readme/55_example.png "Example 55")
```erb
<%= bootstrap_form_for @user do |f| %>


<%= f.email_field :email, disabled: true, size: 18 %>

<%= f.password_field :password, disabled: true, size: 18 %>

<%= f.text_area :comments, disabled: true, rows: 2, cols: 18 %>

<%= f.text_field :status, disabled: true, size: 18 %>

<%= f.number_field :misc, label: "Number", disabled: true %>

<%= f.radio_button :preferences, 1, disabled: true %>

<%= f.check_box :terms, disabled: true %>

<%= f.select :type, [1,2,3], {}, disabled: true %>

<%= f.datetime_field :created_at, disabled: true %>


<%= f.primary disabled: true %>
<% end %>
```

Generated HTML:

```html




Email





Password





Comments





Status





Number






1






Terms




Type

1
2
3





Created at




```

## Internationalization

bootstrap_form follows standard rails conventions so it's i18n-ready. See more
here: http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

## Future Compatibility

The Rails team has [suggested](https://github.com/rails/rails/issues/25197) that `form_for` and `form_tag` may be deprecated and then removed in future versions of Rails. `bootstrap_form` will continue to support `bootstrap_form_for` and `bootstrap_form_tag` as long as Rails supports `form_for` and `form_tag`.

## Other Tips and Edge Cases

By their very nature, forms are extremely diverse. It would be extremely difficult to provide a gem that could handle every need. Here are some tips for handling edge cases.

### Empty But Visible Labels

Some third party plug-ins require an empty but visible label on an input control. The `hide_label` option generates a label that won't appear on the screen, but it's considered invisible and therefore doesn't work with such a plug-in. An empty label (e.g. `""`) causes the underlying Rails helper to generate a label based on the field's attribute's name.

The solution is to use a zero-width character for the label, or some other "empty" HTML. For example:

```ruby
label: "​".html_safe
```

or

```ruby
label: "".html_safe
```

## Contributing

We welcome contributions.
If you're considering contributing to bootstrap_form,
please review the [Contributing](/CONTRIBUTING.md)
document first.

## Previous Version

If you're looking for `bootstrap_form` for Bootstrap 4, go [here](https://github.com/bootstrap-ruby/bootstrap_form/tree/bootstrap-4).

## License

MIT License. Copyright 2012-2021 Stephen Potenza (https://github.com/potenza) and others