My question is how to set a field in rails form read only. The following is a selection box in quotes controller. Users are not allowed to change the selection.
<% @quote.test_items.each do |t| %>
<%= f.association :test_items, :label => false, :selected => t.id %>
<% end %>
The app uses simple_form. Thanks so much.
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
Note: A form will still submit an input field that is readonly, but will not submit an input field that is disabled!
I've encountered a similar problem, thankfully, there is a simple resolution.
The basic issue is that if you use :disabled => true
with simple_form you will not see that value back in the controller. When you pass an object from HTML form to later bind it to the model - you need all of those attributes. The :disabled => true
however does not pass any such attribute.
The solution to this is to use :readonly => true
- it will protect the field from user entry and it will still pass the param value back to the controller so you can bind everything to your model.
Good luck.
See https://github.com/plataformatec/simple_form/pull/367
I believe you'd just pass in :disabled => true
. It's been my experience that options 'just work' with simple_form. So in your case:
<% @quote.test_items.each do |t| %>
<%= f.association :test_items, :label => false, :disabled => true, :selected => t.id %>
<% end %>
From the simple_form github repo:
It is also possible to give the :disabled option to SimpleForm, and it'll automatically mark the wrapper as disabled with a css class, so you can style labels, hints and other components inside the wrapper as well.
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