sbilharz / formwandler

Dynamic form objects for rails
MIT License
0 stars 1 forks source link

View helper to generate form template #10

Open sbilharz opened 6 years ago

sbilharz commented 6 years ago

One purpose of formwandler is to take the form logic out of the HTML template. Right now you can configure most of the relevant attributes of fields (like hidden and disabled) in the form class, but you have to make sure yourself that these settings are reflected in the template, which is not DRY.

Currently, the template code for a field that may be hidden or disabled in some cases may look like this:

class MyForm < Formwandler::Form
  field :my_field, model: :my_model, hidden: -> { no_admin? }, disabled: -> { no_admin? || unconfirmed? }, default: -> { controller.current_user.middle_name }

  private

  def no_admin?
    !controller.current_user.admin?
  end

  def unconfirmed?
    !controller.current_user.confirmed?
  end
end
<% if @my_form.field(:my_field).visible? %>
  <%= f.text_field :my_field, disabled: @my_form.field(:my_field).disabled? %>
<% elsif @my_form.field(:my_field).default? %>
  <%= f.hidden_field :my_field %>
<% end %>

What I want is a helper method that does this redundant work for me. If possible, it should even render the whole form with one call. Of course, there are some more things to consider: