Skip to content

Instantly share code, notes, and snippets.

@kirillplatonov
Created August 7, 2021 09:34
Show Gist options
  • Save kirillplatonov/4a8ee60958e6cd90cfc0761fce8661a9 to your computer and use it in GitHub Desktop.
Save kirillplatonov/4a8ee60958e6cd90cfc0761fce8661a9 to your computer and use it in GitHub Desktop.
TailwindFormBuilder
class TailwindFormBuilder < ActionView::Helpers::FormBuilder
ERROR_FIELD_CLASS = "is-invalid"
ERROR_FEEDBACK_CLASS = "invalid-feedback"
def field_class(attribute)
ERROR_FIELD_CLASS if object.errors.key?(attribute)
end
def errors_for(attribute, attrs = {})
return if object.blank?
return unless object.errors.key?(attribute)
message = object.errors[attribute].join(', ').html_safe
class_name = "#{ERROR_FEEDBACK_CLASS} #{attrs[:class]}".strip
@template.tag.p(message, class: class_name)
end
def text_field(method, options = {})
options[:class] = field_class_with_validation(method, options[:class])
super
end
def text_area(method, options = {})
options[:class] = field_class_with_validation(method, options[:class])
super
end
def email_field(method, options = {})
options[:class] = field_class_with_validation(method, options[:class])
super
end
def password_field(method, options = {})
options[:class] = field_class_with_validation(method, options[:class])
super
end
def phone_field(method, options = {})
options[:class] = field_class_with_validation(method, options[:class])
super
end
def number_field(method, options = {})
options[:class] = field_class_with_validation(method, options[:class])
super
end
def date_field(method, options = {})
options[:class] = field_class_with_validation(method, options[:class])
super
end
def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
options[:class] = field_class_with_validation(method, options[:class])
super
end
def select(method, choices = nil, options = {}, html_options = {}, &block)
html_options[:class] = field_class_with_validation(method, html_options[:class])
super
end
private
def field_class_with_validation(attribute, field_class)
return field_class if object.blank?
return field_class unless object.errors.key?(attribute)
return field_class if field_class&.include?(ERROR_FIELD_CLASS)
[field_class, ERROR_FIELD_CLASS].compact.join(' ')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment