I have a large simple_form form with fields that need to be enabled or disabled depending upon where the form's partial gets loaded.
My question is: how do you disable every form input quickly using simple_form helpers / wrappers?
Simple Form's documentation explains how disabled: true
can be used to disable a single input field:
<%= simple_form_for @user do |f| %>
<%= f.input :username, disabled: true %>
<%= f.button :submit %>
<% end %>
But the documentation is less clear on how I can disable an entire form via simple_form helpers without needing to repeat disabled: true
on literally every form input.
I tried passing disabled: true
and readonly: true
to simple_form's :wrapper_mappings
option, but that isn't working.
I load the form via a partial to define simple_form display variables. This works:
#user/show.html.erb:
<%= render partial: 'shared/form', locals: {questionnaire: @questionnaire, readonly_state: true, disabled_state: true, bootstrap_form_class: 'form-horizontal'} %>
However, readonly_state and disabled_state do not work unless I pass them to every form input:
# shared/_form.html.erb
<%= simple_form_for(@questionnaire, :html => {:class => bootstrap_form_class},
:wrapper_mappings => {check_boxes: :vertical_radio_and_checkboxes, file: :vertical_file_input,
boolean: :vertical_boolean }) do |f| %>
<%= f.input :username, disabled: disabled_state, hint: 'You cannot change your username.' %>
<%= f.input :email, disabled: disabled_state %>
<%= f.input :city, disabled: disabled_state %>
<%= f.input :country, disabled: disabled_state %>
. . .
<%= f.button :submit %>
<% end %>
You can quickly see how repetitious this gets with a large form.
You can create a custom wrapper that disables the input like this:
# config/initializers/simple_form.rb
config.wrappers :disabled_form do |b|
b.use :input, disabled: true, readonly: true
end
And in the form use:
<%= simple_form_for @model, wrapper: :disabled_form %>
<%= f.input :field %>
...
<% end %>
Depending on the amount of different inputs in the form, you might need to create more custom wrappers and use a wrapper_mapping
in the disabled form.
Funny:
<%= f.input :username, disabled: true %>
Generated 'disabled' class for element.
<%= f.input :username, input_html: {disabled: true} %>
Don't do this :)
But you can do these:
<%= f.input :username, input_html: {readonly: :true} %>
or
<%= f.input :username, input_html: {disabled: :true} %>
Where (unlike readonly) the cursor changes to 🛇
Just a suggestion, you can achieve the behaviour using jquery by setting $('.form input').prop('disabled', true);
where form
is your form class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With