【问题标题】:Using tr as label-input wrapper in simple-form使用 tr 作为简单形式的标签输入包装器
【发布时间】:2013-01-14 20:46:26
【问题描述】:

我可能是老派,我曾多次尝试 div/span 并曾一度发誓不使用表格,但表格只是有一些很好的用途,其中一个,恕我直言,是一种形式。我更喜欢用不同的背景颜色来遮蔽我的标签字段。我试过可能的方法,但如果输入(实际上是任何一个)边溢出宽度,它会弄乱标签背景。我会考虑另一种尝试,但我真的更喜欢表格方法。

在 2.x 中,我将配置设置为:

config.wrappers :tag => :tr, :class => :input,
  :hint_class => :field_with_hint, :error_class => :field_with_errors do |b|

  b.use :label, :wrap_with => {:tag => :td, :class => :label}
  b.use :input, :wrap_with => {:tag => :td, :class => :input}
  b.use :hint,  :wrap_with => { :tag => :span, :class => :hint }
  b.use :error, :wrap_with => { :tag => :caption, :class => :error }

效果很好!除了错误。我第一次把它当作一个跨度,它走到了桌子的顶部。然后我将它设置为标题,至少在 Safari 中,它结束 tbody 并放入标题并启动另一个 tbody - 但它搞砸了表格流程。

有没有办法强制错误出现在输入包装器中?还是有其他方法?我什至会接受(也许这是我应该做的)将错误放在主要消息中,例如脚手架方法。直到我开始写这篇文章时才考虑到这一点,但我想我不能使用简单的表单错误内容并回到脚手架方法。

至少我认为你可以做到。例如,我不知道(并且无法在文档中找到 - 但我看起来并不难!)您可以将常规 form_for 输入(例如 f.text_field)与 f.input 混合使用。非常适合将 City、St、Zip 放在一行中。

【问题讨论】:

标签: ruby-on-rails-3 simple-form


【解决方案1】:

我想我应该回答我自己的问题。我最终没有使用 Simple Forms 错误通知并返回脚手架方法。

我将包装器配置如下:

config.wrappers :tag => :tr, :class => :input,
  :hint_class => :field_with_hint, :error_class => :field_with_errors do |b|
    b.use :label, :wrap_with => {:tag => :td, :class => :label}
    b.use :input, :wrap_with => {:tag => :td, :class => :input}

为错误写了一个辅助方法:

def show_form_errors(instance)
  if instance.errors.any?
    errors = content_tag(:h2, pluralize(instance.errors.count, "error") +"prohibited this project from being saved:")
    list = content_tag :ul do
      e = ""
      instance.errors.full_messages.each do |msg|
        e <<"<li>#{msg}</li>"
      end
      e.html_safe
    end
    return content_tag(:div, (errors + list),:id => "error_explanation").html_safe
  end
end

# instead of
  # = f.error_notification
# I used
  # = show_form_errors(@event)

由于我如何在表格行上定义边框(只是边框底部)并添加 !important 以用红色边框包裹 tr ,因此不得不调整 CSS 的 error_explanation:

.field_with_errors {
  padding: 2px;
  border:solid 3px red!important;
  background-color:pink;
}

效果很好,我对这种方法很满意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 2015-08-17
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    相关资源
    最近更新 更多