Forum: Ruby on Rails Repopulating form after validation error

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Tom E. (Guest)
on 2007-07-25 13:12
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 %>
<table>
    <tr>
      <td><label>name:</label> </td>
    </tr>
    <tr>
      <td><%= text_field_tag :name, $name, :size => 25 %></td>
    </tr>
Tom E. (Guest)
on 2007-07-25 13:15
woops, didn't mean to post just then.  In the above code I did have
this:

<% form_tag( :action => :send_mail ) do %>
  <table>
     <tr>
        <td><label>name:</label> </td>
     </tr>
     <tr>
        <td><%= text_field_tag :name, params[:name}, :size => 25 %></td>
     </tr>

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
Jeff E. (Guest)
on 2007-07-26 02:46
(Received via mailing list)
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>
Tom E. (Guest)
on 2007-07-26 15:34
Thanks Jeff, hadn't realised I needed to use render there, I was doing a
redirect.  It works now and no nasty globals misuse.
This topic is locked and can not be replied to.