Флажки Bootstrap 3 + simple_forms
Я пытаюсь интегрировать bootstrap 3 с simple_forms (от master).
Сейчас у меня есть следующее:
конфиг/Инициализаторы/simple_form.rb:
SimpleForm.setup do |config|
config.wrappers :default, class: :input,
hint_class: :field_with_hint, error_class: :field_with_errors do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label_input
b.use :hint, wrap_with: { tag: :span, class: :hint }
b.use :error, wrap_with: { tag: :span, class: :error }
end
config.default_wrapper = :default
config.boolean_style = :nested
config.button_class = 'btn'
end
конфиг/Инициализаторы/simple_form_bootstrap.rb:
SimpleForm.setup do |config|
config.input_class = 'form-control'
config.wrappers :bootstrap, tag: 'div', class: 'form-group', error_class: 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper tag: 'div', class: 'controls' do |ba|
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
config.wrappers :prepend, tag: 'div', class: "form-group", error_class: 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper tag: 'div', class: 'controls' do |input|
input.wrapper tag: 'div', class: 'input-prepend' do |prepend|
prepend.use :input
end
input.use :hint, wrap_with: { tag: 'span', class: 'help-block' }
input.use :error, wrap_with: { tag: 'span', class: 'help-inline' }
end
end
config.wrappers :append, tag: 'div', class: "form-group", error_class: 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper tag: 'div', class: 'controls' do |input|
input.wrapper tag: 'div', class: 'input-append' do |append|
append.use :input
end
input.use :hint, wrap_with: { tag: 'span', class: 'help-block' }
input.use :error, wrap_with: { tag: 'span', class: 'help-inline' }
end
end
config.default_wrapper = :bootstrap
end
приложение/просмотров/изобретают/сессии/new.html.haml
%div.panel.panel-auth
%div.panel-heading
%h3.panel-title Sign in
%div.panel-body
= simple_form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f|
.form-inputs
= f.input :email, :required => false, :autofocus => true
= f.input :password, :required => false
= f.input :remember_me, :as => :boolean if devise_mapping.rememberable?
.form-actions
= f.button :submit, "Sign in"
%hr
= render "devise/shared/links"
Но сгенерированный HTML неверен. Ну, это правильно в соответствии с BS2, но неправильно для BS3. Вот он:
<div class="form-group boolean optional user_remember_me">
<label class="boolean optional control-label" for="user_remember_me">
Remember me
</label>
<div class="controls">
<input name="user[remember_me]" type="hidden" value="0">
<label class="checkbox">
<input class="boolean optional form-control" id="user_remember_me" name="user[remember_me]" type="checkbox" value="1">
</label>
</div>
</div>
Но на самом деле это должно быть что-то вроде:
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
Вероятно, можно исправить этот хакинг вокруг оберток, но я не могу заставить его работать.
Может ли кто-нибудь дать мне несколько советов по этому поводу?
Приветствия
Ответы
Ответ 1
Как вы сказали, вы можете заставить его работать с пользовательской оболочкой:
config.wrappers :checkbox, tag: :div, class: "checkbox", error_class: "has-error" do |b|
# Form extensions
b.use :html5
# Form components
b.wrapper tag: :label do |ba|
ba.use :input
ba.use :label_text
end
b.use :hint, wrap_with: { tag: :p, class: "help-block" }
b.use :error, wrap_with: { tag: :span, class: "help-block text-danger" }
end
Что вы тогда ссылаетесь на свой ввод:
= f.input :remember_me, :as => :boolean, :wrapper => :checkbox if devise_mapping.rememberable?
Обратите внимание, что это не будет работать для collection_check_boxes:
= f.input :roles, as: :check_boxes, wrapper: :checkbox, collection: @employee_roles, label: false
Вы можете попробовать взломать пользовательский ввод для последнего случая, но это немного грязно. Возможно, кто-то еще знает лучший способ... и, возможно, simple_form наверняка догонит бутстрап 3.
Ответ 2
Следующая конфигурация отлично работает для меня с бутстрапом 3:
SimpleForm.setup do |config|
...
config.boolean_style = :inline
...
end
Простая пользовательская обертка
config.wrappers :inline_checkbox, :tag => 'div', :class => 'checkbox', :error_class => 'has-error' do |b|
b.use :html5
b.use :placeholder
b.use :label_input
end
Использование:
= f.input :remember_me, :label => t('user.remember_me'), :as => :boolean, :wrapper => :inline_checkbox
Ответ 3
Я нашел очень простое решение для флажков Bootstrap 3. Предполагая, что у вас уже настроена оболочка bootstrap 3, все, что мне нужно было сделать, это добавить пользовательский ввод в app/inputs
как checkbox_input.rb
:
class CheckboxInput < SimpleForm::Inputs::BooleanInput
# this exists to make the default 'boolean' css class in the form-group to be 'checkbox' instead
end
и использовать его через:
= f.input :remember_me, :as => :checkbox if devise_mapping.rememberable?
Это изменит значение css boolean
на form-group
как checkbox
, которое получит правильный стиль.
Аналогично, вот версия для radio-inline
class RadioInlineInput < SimpleForm::Inputs::CollectionRadioButtonsInput
# by default, this omits labels. You should use f.label before this to stick a label where you would like.
def initialize(builder, attribute_name, column, input_type, options = {})
super(builder, attribute_name, column, :radio_buttons, {label: false}.merge(options))
end
def item_wrapper_class
'radio-inline'
end
end
Используется как:
= f.label :frequency
= f.input :frequency, collection: @membership_plan.interval_frequencies, as: :radio_inline
Ответ 4
Вот быстрый способ исправить проблему флажка, пока мы ожидаем, что Rafael выполнит Bootstrap3: https://github.com/wtfiwtz/simple_form_bootstrap3/commits/master
Убедитесь, что вы добавили "config.bootstrap3 = true" в ваш инициализатор...
Ответ 5
У меня есть следующие требования для моего флажка:
<div class="checkbox">
<input type="hidden" value="0" name="...">
<label>
<input type="checkbox" value="1" name="..."> Label text
</label>
</div>
Скрытый ввод был извлечен из метки, поскольку он не проверяет флажок на щелчке метки. Я не знаю, почему, но я не смог создать такой html, просто используя config, так что здесь config + пользовательский класс ввода
# Config
config.wrappers :checkbox, tag: :div, class: "checkbox", error_class: "has-error" do |b|
# Form extensions
b.use :html5
b.use :placeholder
b.use :input
b.use :hint, wrap_with: { tag: :p, class: "help-block" }
b.use :error, wrap_with: { tag: :span, class: "help-block text-danger" }
end
# Input goes to app/inputs/inline_checkbox_input.rb
class InlineCheckboxInput < SimpleForm::Inputs::Base
def input
out = ''
out << @builder.hidden_field(attribute_name, value: 0).html_safe
out << "<label>"
out << @builder.check_box(attribute_name, {}, 1, nil)
out << "#{options[:label]}</label>"
out
end
end
# Usage
= f.input :name, :label => 'Label text', :wrapper => :checkbox, :as => :inline_checkbox
Ответ 6
Вы можете просто использовать это:
<%= f.input :remember_me, as: :boolean, :label => false, :inline_label => "Remember me" if devise_mapping.rememberable? %>