Last active
July 30, 2020 09:34
-
-
Save herko/031de5a44721e6d50e32012eb51dbf25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationFormBuilder < ActionView::Helpers::FormBuilder | |
def form_group(method, options = {}, &block) | |
content = @template.capture(&block) | |
content += help_block_with_errors(method) if object.errors[method].any? | |
options[:class] ||= '' | |
options[:class] += ' form-group' | |
options[:class] += ' has-error' if object.errors[method].any? | |
@template.content_tag :div, content, options | |
end | |
def label(method, text = nil, options = {}, &block) | |
text ||= @template.t(".#{method}.label") | |
options[:class] ||= '' | |
options[:class] += ' control-label' | |
super(method, text, options, &block) | |
end | |
%w(text_field number_field date_field email_field password_field text_area).each do |field_helper| | |
define_method field_helper do |method, options = {}| | |
options[:class] ||= '' | |
options[:class] += ' form-control' | |
options[:placeholder] ||= @template.t(".#{method}.placeholder", default: '') | |
super(method, options) | |
end | |
end | |
def submit(value = nil, options = {}) | |
unless value.is_a? String | |
options = value | |
value = @template.t('.submit') | |
end | |
super(value, options) | |
end | |
private | |
def help_block_with_errors(method) | |
@template.content_tag( | |
:span, object.errors[method].join(', '), class: 'help-block has-error' | |
) | |
end | |
end | |
# Disable .field_with_errors wrapper for invalid forms | |
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| | |
html_tag.html_safe | |
end | |
ActionView::Base.default_form_builder = 'ApplicationFormBuilder' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment