1

I have a simple_form in my rails app that I want to pre-populate some of the fields with URL parameters.

Example URL is:

http://localhost:3000/surveys/new?phone=8675309

This pre-populate the phone field corretly using this code:

<%= simple_form_for @survey, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.input :state, :required => true %>
<%= f.input :zip, :required => true %>
<%= f.input :phone, :required => true, :input_html => { :value => params['phone'] } %>
<% end %>

The problem is if the form is submitted without a required field the form is reloaded but the phone input value is not retained.

If the form is submitted without a value for zip the reloaded page with validation errors in red URL is now:

http://localhost:3000/surveys

If, say, the state field is correct but no zip code the form is reloaded with an error msg saying zip is required.

The state value is retained however the phone is not.

I guess it has to do with :value => params['phone'] in the f.input for the phone.

Is there anyway I can populate the simple_form with URL paramenters on it's initial load and have those value retained if the serverside validation fails?

Many thanks.

Rudi Starcevic
  • 645
  • 1
  • 11
  • 17

2 Answers2

0

Remove the :value from your view:

<%= f.input :phone, :required => true %>

and use this URL:

http://localhost:3000/surveys/new?survey[phone]=8675309

That should generate the "standard" survey parameter hash expected by the controller. In my test, that works the same as if the user had typed in the value, with the usual validation handling.

Inside the controller, the hash is called params[survey] with individual parameters represented as params[survey][phone], params[survey][zip], etc.

With the help of this answer, I found that you can generate the URL with the link_to signature link_to(body, url_options = {}, html_options = {}):

<%= link_to 'New survey', { :controller => "surveys", 
                            :action => "new", 
                            :survey => { :phone => "8675309", :zip => "10001" } },
                          { :target => "_blank" } %>

Note that url_options is the first hash, and within that hash you have a survey hash for pre-loading values. Finally comes the optional hash of html_options (where I added target="_blank" for illustration purposes).

Community
  • 1
  • 1
Mark Berry
  • 17,843
  • 4
  • 58
  • 88
0

Thanks Mark,

I re-posted this question again a while back and it was answered corretly here:

Rails simple_form server side validations lost URL params

Community
  • 1
  • 1
Rudi Starcevic
  • 645
  • 1
  • 11
  • 17