user1593518
user1593518

Reputation: 61

How to pass multiple params in a text_field_tag

Ok, so i am trying to get the value from one textfield and pass it to two different methods in a viewController when the user clicks on either the "Add" button or "search" button (so if user presses search button it geoes to search method and if user clicks add button it goes to add method), so far this code does the trick but i dont like that there has to be two text fields, should i maybe use button_to's? and if so how would that look? Thx

  <p><%= form_tag :controller => 'projects', :action => 'search', :method => 'get' do %>

  <%= text_field_tag :search, params[:search] %>
  <%= submit_tag "search" %>
  <%= link_to_function "Clear", "$('search_field').clear()" %>
  <% end %>
  </p>

  <p><%= form_tag :controller => 'projects', :action => 'add_project_to_user' do %>
  <%= text_field_tag :text, params[:text] %>
  <%= submit_tag "Add" %>
  <%= link_to_function "Clear", "$('search_field').clear()" %>
  <% end %>
  </p>

Upvotes: 0

Views: 2660

Answers (2)

Peter Degen-Portnoy
Peter Degen-Portnoy

Reputation: 796

Thanks for the clarifications. The limitation is with HTML, not Rails: A form can have only one action. That is: one controller & action.

There are few options. You can branch your behavior within your controller. Have one action that handles either Search or Add, depending on which button is clicked (yes, you can have multiple buttons within the form; there is an old railscasts (Episode 38) on this. However this is rather clunky.

Another option is to use JavaScript to set the action on the form in response to the button click.

Upvotes: 2

Joel Friedlaender
Joel Friedlaender

Reputation: 2191

Have one form with two submit buttons. Put an "onclick" event on each button. When the button is clicked, it can use javascript to change the action of the form before the submit takes place. Each button would obviously change the action appropriate to itself (search or add).

Upvotes: 0

Related Questions