Repopulating form after validation error


#1

Hi,
I have a contact form, if a user enters an invalid email I redirect
them back to the form to correct it. I didn’t want users to have to
re-enter all the data so I want to repopulate the valid fields for them.
The only way I can currently get this to work is by using globals, which
doesn’t feel right. Is there another way?

<% form_tag( :action => :send_mail ) do %>

name:
<%= text_field_tag :name, $name, :size => 25 %>

#2

woops, didn’t mean to post just then. In the above code I did have
this:

<% form_tag( :action => :send_mail ) do %>

which I thought would populate the field if the :name param was set but
it wasn’t working like that. Am i missing something here?

Thanks
T

name:
<%= text_field_tag :name, params[:name}, :size => 25 %>

#3

that should work just fine provided you don’t do a redirect in your
controller upon failure… you need something like

MyController

def send_mail

if request.post?
  if everything validates etc
    flash[:notice] = 'Message sent'
    redirect_to :action => :message_sent
  else
    render :action => :contact_form
  end
end

end

end

note that if there was an error you render an action, not redirect to
it. if you redirect you are responsible for preserving all params
yourself.

On Jul 25, 5:15 am, Tom E. removed_email_address@domain.invalid


#4

Thanks Jeff, hadn’t realised I needed to use render there, I was doing a
redirect. It works now and no nasty globals misuse.