jasin_89
jasin_89

Reputation: 2001

Rails form fields empty after submitting form

This is my form:

<%= form_tag("/adverts", :method => "get") do %>
Order by: 
<%= select_tag :order_by, options_for_select([['Ascending', 'ASC'], ['Descending', 'DESC']])%>

<%= text_field_tag :text%>

<%= submit_tag 'Change' %>
<% end %>

In my Adverts controller, index method, for now I am not doing anything and I can see that it is getting correct values from form,

=>but when page reloads after submission, fields values are empty but I want them to retain values.

So if I enter some text in text field, that text will still be there after submitting form .

Upvotes: 2

Views: 3199

Answers (2)

Mischa
Mischa

Reputation: 43298

Like this:

<%= select_tag :order_by, options_for_select([['Ascending', 'ASC'], ['Descending', 'DESC']], params[:order_by]) %>

and:

<%= text_field_tag :text, params[:text] %>

See the API for options_for_select and text_field_tag.

Upvotes: 5

Matt
Matt

Reputation: 14038

You need to create the form for an object if you want it to automatically get the objects values on reload.

<%= form_for @object do |form| %>
  <%= form.text_field :name %> <!-- automatically gets re-populated with the value of @object on postback -->
  <%= form.submit %>
<% end %>

If you really want to use form tags instead of a builder then you need to set the values manually after postback

<%= text_field_tag :text, some_string_value %>

Upvotes: 1

Related Questions