Last active
December 19, 2021 19:46
-
-
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
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
# 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 |
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
# 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 |
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
# 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