Assign class to form in form builder

Is it possible to assign a given class to the form with a custom form builder? e.g. I would like to asssign to all the forms built with form_with ..., builder: MyFormBuilder do ... always the class ‘my_form’

A couple of ways I could think of:

1. Create a form helper

def my_form_with(*args, **kwargs, &blk)
  merged_classes = class_names(kwargs[:class], 'my_form')
  form_with *args, **kwargs, builder: MyFormBuilder, class: merged_classes, &blk
end

Then use my_form_with in place of form_with.

2. Create an args helper

def my_form
  { builder: MyFormBuilder, class: 'my_form' }
end

Then use it with form_with:

<%= form_with …, **my_form, other: args do %>
  …
<% end %>

You could of course monkeypatch form_with, but I recommend avoiding that. It’s better to be clear on how you configure the form.

1 Like

Hi Max,

Thanks a lot! I went with 1) and it works like a charm.