Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tmaier
Last active December 19, 2021 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmaier/22966c6bddac86e3612c8eddc072b919 to your computer and use it in GitHub Desktop.
Save tmaier/22966c6bddac86e3612c8eddc072b919 to your computer and use it in GitHub Desktop.
Sample implementation of hints and error_message for ViewComponent::Form https://github.com/pantographe/view_component-form/issues/36
# frozen_string_literal: true
class Form::ErrorMessageComponent < ViewComponent::Form::FieldComponent
def call
tag.p messages, class: 'mt-0.5 text-sm text-red-600'
end
def render?
method_errors?
end
private
def messages
safe_join(method_errors, tag.br)
end
end
# frozen_string_literal: true
class FormBuilder < ViewComponent::Form::Builder
# Set the namespace you want to use for your own components
namespace 'Form'
def error_message(method, options = {})
render_component(:error_message, @object_name, method, objectify_options(options))
end
def hint(method, text = nil, options = {}, &block)
render_component(:hint, @object_name, method, text, objectify_options(options), &block)
end
end
# frozen_string_literal: true
class Form::HintComponent < ViewComponent::Form::FieldComponent
attr_reader :attribute_content
def initialize(form, object_name, method_name, content_or_options = nil, options = nil)
options ||= {}
content_is_options = content_or_options.is_a?(Hash)
if content_is_options
options.merge! content_or_options
@attribute_content = nil
else
@attribute_content = content_or_options
end
super(form, object_name, method_name, options)
end
def call
content_or_options = nil
content_or_options = content || attribute_content if content.present? || attribute_content.present?
tag.p content_or_options, class: 'mt-1 text-sm text-gray-500'
end
def render?
content.present? || attribute_content.present?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment