代码之家  ›  专栏  ›  技术社区  ›  Jonathan

Rails验证|将类添加到周围<div>

  •  0
  • Jonathan  · 技术社区  · 16 年前

    问题。错误验证的默认行为是在输入字段周围使用FIELDWERROR样式的div,如下所示

    <div class="type-text" id="pre_negotiation_value_div">
    <label for="contract_budget_holder">Budget Holder</label>
    <div class="fieldWithErrors">
    <input id="contract_budget_holder"name="contract[budget_holder]" size="30" type="text" value="" />
    </div>
    </div>
    

    我试图实现的是,用一个已分类的div标记包围标签和输入字段,如下所示:

    <div class="type-text fieldWithErrors" id="pre_negotiation_value_div">
    <label for="contract_budget_holder">Budget Holder</label>      
    <input id="contract_budget_holder"name="contract[budget_holder]" size="30" type="text" value="" />      
    </div>
    

    我是Rails新手,如果这非常简单,我向您道歉!

    谢谢你的帮助。

    乔纳森

    2 回复  |  直到 16 年前
        1
  •  2
  •   pjb3    16 年前

    要做到你想要的并不容易,但如果你有这样的ERB:

    <div id="pre_negotiation_value_div" class="type-text">
      <%= f.label :name %>
      <%= f.text_field :name %>
    </div>          
    

    您将得到如下HTML:

    <div id="pre_negotiation_value_div" class="type-text">
      <div class="fieldWithErrors"><label for="foo_name">Name</label></div>
      <div class="fieldWithErrors"><input id="foo_name" name="foo[name]" size="30" type="text" value="" />
    </div>
    

    其中标签和文本_字段的周围都有fieldWithErrors div。根据您想要的样式,这可能就足够了。如果还不够好,您将不得不执行如下自定义帮助程序:

    class ActionView::Helpers::FormBuilder
      def labeled_input(method, options={}, &block)
        (options[:class] ||= "") << " fieldWithErrors" if @object.errors.on(method)
        ActionView::Helpers::InstanceTag.send(:alias_method, :original_error_wrapping, :error_wrapping)
        ActionView::Helpers::InstanceTag.send(:define_method, :error_wrapping,
          Proc.new {|html_tag, has_error| html_tag})
        @template.concat(@template.content_tag(:div, @template.capture(&block), options))
      ensure
        ActionView::Helpers::InstanceTag.send(:alias_method, :error_wrapping, :original_error_wrapping)
        ActionView::Helpers::InstanceTag.send(:remove_method, :original_error_wrapping)
      end
    end
    

    把它放进去 config/initializers/labeled_input.rb . 这是一堆Ruby meta foo,但它所做的是将“fieldWithErrors”类放在外部div上 error_wrapping 方法 InstanceTag 这样,内部标签和文本字段标记周围就不会有“fieldWithErrors”div。您在ERB中的使用方式如下:

    <% f.labeled_input :name, :id => "pre_negotiation_value_div", :class => "type-text" do %>
      <%= f.label :name %>
      <%= f.text_field :name %>
    <% end %>
    
        2
  •  0
  •   Peter    15 年前

    RAILS 3更新

    我正在将我的应用程序更新到rails 3。如果您使用过此方法并且正在升级,您将收到一些弃用警告,并且表单字段会出现两次或多次。

    要解决这些问题,请执行以下操作:

    1) 更改标记为_input.rb的检查错误的行。这将停止不推荐警告访问错误:

    (options[:class] ||= "") << " fieldWithErrors" unless @object.errors[method].empty?
    

    2) 在“确保”之前更改标有_input.rb的行。这将停止表单元素多次出现:

    @template.content_tag(:div, @template.capture(&block), options)
    

    3) 在调用标记的_输入的视图文件中,使用<%=而不是<%。这可以防止出现弃用警告。