pantographe / view_component-form

Rails FormBuilder for ViewComponent
MIT License
204 stars 16 forks source link

Docs for adding a custom field helper #126

Closed Spone closed 2 months ago

Spone commented 1 year ago

Explain how to add a custom field helper to a custom FormBuilder (such as switch_box, image_field etc.)

joelzwarrington commented 5 months ago

https://github.com/pantographe/view_component-form/issues/157 is a duplicate of this issue (or adding this documentation would resolve that issue).

It is my understanding that at a minimum, one can add a custom form field helper by adding their method to the builder:

def foo(method, options = {})
  render_component(:foo, @object_name, method, objectify_options(options))
end

and then

class Foo < ViewComponent::Form::FieldComponent # or ViewComponent::Form::BaseComponent
end

Then, if one would like further customization, they can add positional arguments.

def foo(method, arg_1, arg_2 = :some_default, options = {})
  render_component(:foo_with_positional_args, @object_name, method, arg_1, arg_2, objectify_options(options))
end

and then

class FooWithPositionalArgs < ViewComponent::Form::FieldComponent # or ViewComponent::Form::BaseComponent
  attr_reader :arg_1, :arg_2

  def initialize(form, object_name, method_name, arg_1, arg_2, options = {}) 
    @arg_1 = arg_1
    @arg_2 = arg_2

    super(form, object_name, method_name, options)
  end
end

Would you be open to me having a stab at this?

Spone commented 5 months ago

Definitely! Thanks 🙏