Access model errors in input
enrique-fernandez-polo opened this issue · 2 comments
enrique-fernandez-polo commented
Hello there!
I am adapting all the inputs to daysiui The problem I have is that I want to add a class conditionally to the input. I do knot how to access the model in MyInputComponent
like in the labeled
method.
I want to add a class to the input in the case of an error
class ApplicationForm < Superform::Rails::Form
include Phlex::Rails::Helpers::Pluralize
class MyInputComponent < Superform::Rails::Components::InputComponent
def view_template(&)
input(**attributes.merge(class: 'input input-bordered w-full max-w-xs'))
end
end
class MyLabelComponent < Superform::Rails::Components::LabelComponent
def view_template(&content)
content ||= proc { field.key.to_s.titleize }
span(**attributes.merge(class: 'label-text'), &content)
end
end
class Field < Superform::Rails::Form::Field
def input(**attributes)
MyInputComponent.new(self, attributes:)
end
def label(**attributes)
MyLabelComponent.new(self, attributes:)
end
end
def labeled(component)
label class: 'form-control w-full max-w-xs' do
div class: 'label' do
render component.field.label
end
render component
div class: 'label' do
span class: 'text-error label-text-alt' do
model.errors.full_messages_for(component.field.key).join(', ')
end
end
end
end
def submit(text)
button(class: 'btn btn-primary', type: :submit) { text }
end
end
rompetomp commented
I found you can get the object in the component by calling @field.parent.object
, so you can get the fields errors with @field.parent.object.errors[:@field.key]
.
I agree it's annoying, but currently the only way I found.