Search code examples
ruby-on-railstwitter-bootstrapsimple-formbootstrap-5

How do you write a toggle switch with Bootstrap 5 and simple_form


https://getbootstrap.com/docs/5.0/forms/checks-radios/#switches. A toggle switch is another way to format a boolean checkbox.

<%= simple_form_for(@location) do |form| %>
  <%= form.input :pre1890 %>

Results in a default checkbox.Screenshot of default I'd like a toggle switch or maybe a labeled button. Toggle from Bootstrap website

I think I've seen JavaScript solutions for pre Bootstrap 5, but if JavaScript is required I'll live with the default. Thank you.


Solution

  • Add this config in config/initializers/simple_form.rb

      config.wrappers :bootstrap_toggle, tag: 'div', class: 'form-check form-switch', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b|
        b.use :html5
        b.optional :readonly
        b.use :label, class: 'form-check-label'
        b.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
        b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' }
        b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' }
      end
    

    and configure this to boolean

    config.wrapper_mappings = {
      boolean:       :bootstrap_toggle,
      # ....
    }
    

    NOTE: If you are using bootstrap with simpleform check this https://github.com/heartcombo/simple_form#bootstrap

    Or refer this code

      config.wrappers :vertical_boolean, tag: 'fieldset', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b|
        b.use :html5
        b.optional :readonly
        b.wrapper :form_check_wrapper, tag: 'div', class: 'form-check' do |bb|
          bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
          bb.use :label, class: 'form-check-label'
          bb.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' }
          bb.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' }
        end
      end
    

    at https://github.com/heartcombo/simple_form/blob/123d3b3822cb8a23c6216261f32d5e1af139a087/lib/generators/simple_form/templates/config/initializers/simple_form_bootstrap.rb#L66