rubymonolith / superform

Build highly customizable forms in Rails
MIT License
263 stars 14 forks source link

Access model errors in input #42

Open enrique-fernandez-polo opened 1 week ago

enrique-fernandez-polo commented 1 week ago

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