Search code examples
ruby-on-railsruby-on-rails-2ruby-1.8.7

prepopulate form with data in rails 2


I have a form with some fields in my rails 2 application and I want to prepopulate the value from what was entered before. The parameters values are in the url

here is the code for the form:

<% form_tag({:controller => "articles", :action => "search"}, :method => "get") do %>
    <%= label_tag("start_date") %>
    <%= text_field_tag("start_date","", :type => "date") %>

    <%= text_field_tag "username", "", :placeholder => "username" %>
    <%= text_field_tag "email", "",  :type => "email" %>

    <%= select_tag "status", options_for_select([["status", ""],"approved", "unchecked"])%>

    <%= submit_tag("Search") %>
  <% end %>

I have tried to use for instance @username = params[:username] in the controller but I still get an empty field


Solution

  • Problem is you're providing empty content for the field:

    <%= text_field_tag "username", "", :placeholder => "username" %>
    

    Rails doesn't automatically takes instance variables based on the field name, so if your controller defines a @username variable, you have to explicitly use it:

    <%= text_field_tag "username", @username, :placeholder => "username" %>