gpt4 book ai didi

html - Rails field_error_proc 覆盖搞乱 html 结构

转载 作者:行者123 更新时间:2023-11-28 00:54:50 24 4
gpt4 key购买 nike

在 Rails 应用程序中,我重写了 field_error_proc 以允许显示内联错误,如下所示:

enter image description here

这样做的代码如下所示

ActionView::Base.field_error_proc = proc { |html_tag, instance|
html = %(<div class="field_with_errors">#{html_tag}</div>).html_safe

form_fields = %w[textarea input select]

elements = Nokogiri::HTML::DocumentFragment.parse(html_tag).css 'label, ' + form_fields.join(', ')

elements.each do |e|
next unless form_fields.include?(e.node_name)
errors = [instance.error_message].flatten.uniq.collect { |error| "#{instance.method_name.humanize} #{error}" }
html = %(<div class="field_with_errors">#{html_tag}</div><small class="form-text error-text">&nbsp;#{errors.join(', ')}</small>).html_safe
end

html
}

这对普通输入工作正常,因为它们被正常包装。

当输入环绕某些东西时,问题就来了,我希望 field_with_errors div 像 select2 下拉菜单或自定义输入组一样环绕:

<div class="split-daterange-picker form-control daterange-picker" id="">
<input class="start-date" placeholder="Requested Dates" type="text" name="housing_lead[start_date]">
<span class="separator"></span>
<input class="end-date" placeholder="Requested Dates" type="text" name="housing_lead[end_date]">
</div>

我正在使用 2 个输入,它们基本上充当单个表单字段,如下所示: enter image description here

但问题是当输入被包装在 field_with_errors div 中时,它看起来像下面这样:

enter image description here

我基本上想做的是将 split-daterange-picker 包装在 field_with_errors div 中,这样我就可以适本地设置样式并在之后附加错误消息。我该怎么做

最佳答案

我知道没有办法用 ActionView::Base.field_error_proc 来做到这一点。但是您可能会得到一些与自定义表单构建器一起工作的东西,如 this answer 中所讨论的那样。 .

class PrettyFormBuilder < ActionView::Helpers::FormBuilder  
def split_daterange_picker(start_field, end_field, options = {})
options[:wrapper_class] ||= []
if @object.errors[start_field].present? || @object.errors[end_field].present?
options[:wrapper_class] << 'field_with_errors'
end
datepickers = text_field(start_field) + text_field(end_field)
@template.content_tag(:div, datepickers, class: options[:wrapper_class])
end
end

关于html - Rails field_error_proc 覆盖搞乱 html 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52998937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com