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
If your field has a default, you will want to set it from the "show" action for the form:
or directly on the template (less good because uses an
||
every time and adds more controller data to view):The second arg to text_field_tag is the value to fill in the field with. Try something like this: