85

I have a form_for written in the following manner:

<div class="field">
    <%= location.label :city %>
    <%= location.text_field :city, :disabled=>true%>
</div>
<div class="field">
    <%= location.label :country %>
    <%= location.text_field :country, :disabled=>true%>
</div>

As you can see the 2 textfield are disabled because they are autofilled by a jquery function and I don't want let the user handle them. The problem is that in this way, the view doesen't pass that parameters to the controller because are disabled !!! Is there any other way to pass not editable text_field to the controller, taking care that I don't want to use hidden field because I want to show the results to the user inside a textbox

TNX

Joe
  • 1,747
  • 3
  • 17
  • 24

2 Answers2

201

Make it readonly !

<%= location.text_field :country,:readonly => true%>
krunal shah
  • 16,089
  • 25
  • 97
  • 143
  • 9
    Spot on with this. The [W3 specification for forms](http://www.w3.org/TR/html4/interact/forms.html#h-17.12.1) distinguishes `disabled` and `read-only` and makes it clear that disabled inputs should not be submitted with the form data. – Robin Fisher Apr 11 '11 at 11:14
  • 1
    Thanks! I would probably have spent another half hour figuring out why `:disabled => true` wasn't submitting my field. – Tom Harrison Jun 29 '12 at 16:11
  • 3
    But what If I want this field to be accessible on `Create` action? – Clone Jun 23 '13 at 06:59
  • 1
    But with this method anyone can edit before submit. Isn't this vulnerable. – mecyborg Dec 22 '14 at 14:23
  • 1
    Yes, this is vulnerable. The user can use his browser "Developer Tools " (press F12) to remove the `readonly="readonly"` attribute of the `input` tag and edit the text field as he wishes. If you really need this to be safe, remove the input field altogether or validate the form input at the model. That was a very useful answer anyway. – BrunoF Jan 19 '17 at 16:23
1

The trick is to use "object" in conjunction with a label for anything you don't want to change. Here is how you should code it:

<%= location.label(:country, f.object.country) %>
mshasib
  • 11
  • 1