Multiple inputs on a single line with Twitter Bootstrap and Simple Form 2.0

萝らか妹 提交于 2019-12-03 21:49:28

It is possible to have simple_form do this. This places the inputs on one row with a single label:

<%= form.input :city, label: 'City/State/Zip', input_html: {class: 'span3'}, wrapper_html: {class: 'controls controls-row'} do %>
  <%= form.input_field :city, class: 'span1' %>
  <%= form.input_field :state, class: 'span1' %>
  <%= form.input_field :zip, class: 'span1' %>
<% end %>

The 'span*' classes are optional.

Using Bootstrap you can add span wrappers.

config/initializers/simple_form_bootsptrap.rb

config.wrappers :span3, :tag => 'div', :class => 'span3', :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

app/assets/stylesheets/bootstrap_and_overrides.css.less

@red: #B94A48;

.control-group {
  clear: both;
}

.error .controls .help-inline{
  color: @red;
}

.error .control-label {
  color: @red;
}

.error .controls select{
  border: 1px solid #B94A48;
}

_form.html.rb

<%= f.input :city,        :wrapper =>"span3" %>
<%= f.input :region,      :wrapper =>"span3" %>
<%= f.input :postal_code, :wrapper =>"span3" %>

If you do not want the label change the label_input component only to input like this:

config.wrappers :small, :tag => 'div', :class => 'controls inline-inputs' do |b|
  b.use :placeholder
  b.use :input
end

and you don't need to pass :label => false anymore.

The :error_class is not needed since you is not using the error component

An alternative method, and one that doesn't require bootstrap (which I'm assuming provides config.wrappers, since that throws an exception in my project where I'm not using TBS):

<div class="control-group">
    <%= f.input :city,        :wrapper_html => { :class => "inline_field_wrapper" }, :placeholder => "City",        :input_html => { :maxlength => 10}, :label => false %>
    <%= f.input :region,      :wrapper_html => { :class => "inline_field_wrapper" }, :placeholder => "Region",      :input_html => { :maxlength => 5},  :label => false %>
    <%= f.input :postal_code, :wrapper_html => { :class => "inline_field_wrapper" }, :placeholder => "Postal Code", :input_html => { :maxlength => 10}, :label => false %>
</div>

Then in your css:

.inline_field_wrapper {
    display: inline-block;
}

My solution for horizontal bootstrap forms:

.control-group
  = f.label :password
  .controls.controls-row
    = f.input_field :password, :class => 'span2'
    = f.input_field :password_confirmation, :class => 'span2'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!