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

  • 相关阅读:
    [转]跨语言通信方案比较
    C#三种定时器
    Java优化技巧
    websocket初探
    [转]远远走来一个绿茶婊
    赠与今年的大学毕业生-----------胡适
    HDU3068 回文串 Manacher算法
    OpenCV安装与配置
    tkinter事件机制
    哈夫曼压缩
  • 原文地址:https://www.cnblogs.com/ilazysoft/p/2159485.html
Copyright © 2011-2022 走看看