Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Restoring contents of non-model form that uses form_tag

I'm making good progress with my first Rails app (using Rails 3). The MVC interaction is all going fine, but I'm having difficulty with a form that doesn't relate directly to a model.

I'm using form_tag, and in the case of success, everything behaves fine. However, the handling of errors is somewhat unfriendly. The actual error message is stored in the flash and displayed fine by layouts/application.html, but I'd really like it if the form could remember the contents that the user had just filled in. But it doesn't: all the fields reset to their default values.

I love the way that forms for RESTful actions on objects automatically remember their submitted values, and get highlighted in red if there are errors. I'm fine without the red highlight, but I'd really like it if I could make the form's fields keep the submitted values.

Can anyone advise how to do this?

Excerpts from the relevant files:

views/cardsets/import.html.erb:

<%= form_tag :action => :import_data, :id => @cardset do %>
  ...
  <%= text_field_tag "separator", "", :maxlength => 1 %>
  ...
  <%= text_field_tag "formatting_line" %>
  ...etc (more fields)

controllers/cardsets_controller.rb:

# POST /cardsets/1/import_data
def import_data
  success, message = @cardset.import_data(params, current_user)
  if success
    redirect_to(@cardset, :notice => message)
  else
    flash.now[:error] = message
    render :import
  end
end
like image 965
AlexC Avatar asked Nov 08 '10 23:11

AlexC


2 Answers

The second arg to text_field_tag is the value to fill in the field with. Try something like this:

  <%= text_field_tag "separator", params[:separator], :maxlength => 1 %>
like image 90
jwarchol Avatar answered Sep 26 '22 04:09

jwarchol


If your field has a default, you will want to set it from the "show" action for the form:

# GET
def show_form
  params[:key] = 'default'
end

# POST
def validate_form_and_act
  # Don't set it here to reuse what the user passed.
end

or directly on the template (less good because uses an || every time and adds more controller data to view):

 <%= text_field_tag 'name', params[:key] || 'default' %>