zoukankan      html  css  js  c++  java
  • how to correctly extend form_for / ActionView::Helpers::FormBuilder 兰猫

    I want to extend form builder to add custom methods. But some issues blocks me, i try my best to resolve it, i should share my solution here,wish it can help somebody.

    This is the current situation:

    module Admin::BaseHelper
     
    def field_container(model, method, options = {}, &block)
      css_classes = options[:class].to_a if error_message_on(model, method).present? css_classes << 'withError' end content_tag('p', capture(&block), :class => css_classes.join(' '), :id => "#{model}_#{method}_field")
     
    end

    end

    I want to use method 'field_container' in my view admin/option_types/_form.html.erb:

    <%= f.field_container :name do %>
      <%= f.label :name, t("name") %> <span class="required">*</span><br />
      <%= f.text_field :name %>
      <%= f.error_message_on :name %>
    <% end %>

    But the following gives me: undefined method filed_container for #<ActionView::Helpers::FormBuilder:0xae114dc>

    ActionView::Template::Error (undefined method `field_container' for #<ActionView
    ::Helpers::FormBuilder:0xadc4470>):

    Do not worry, we should  add a new file named form_builder.rb in folder config/initializers of the project. See bellow content:

    class ActionView::Helpers::FormBuilder
      def field_container(method, options = {}, &block)
        @template.field_container(@object_name,method,options,&block)
      end
      def error_message_on(method, options = {})
        @template.error_message_on(@object_name, method, objectify_options(options))
      end
    end
    ActionView::Base.field_error_proc = Proc.new{ |html_tag, instance| "<span class=\"field_with_errors\">#{html_tag}</span>".html_safe }
    

    Done!!

    Thanks,

    Ivan

  • 相关阅读:
    css-使不同大小的图片在固定大小的容器中居中
    js-数组中查找特定元素并返回所有该元素的索引
    js-权威指南学习笔记5
    js-权威指南学习笔记4
    js-权威指南学习笔记3
    JavaScript中的类型转换
    js-权威指南学习笔记2
    通过维基API实现维基百科查询功能
    【代码笔记】iOS-FMDBDemo
    【代码笔记】iOS-自定义switch
  • 原文地址:https://www.cnblogs.com/ilazysoft/p/2159485.html
Copyright © 2011-2022 走看看