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