Common form tag in form helper

Asked by At

I have a form for search bar, which searches the projects based on name. Projects are differentiated by completed projects, in-progress projects and proposal projects. Those three has the same form expect path name. So, I decided to use a common form in helper.

completed, proposal and in-progress projects are used a different actions in projects controller. I have tried differentiate forms by params[:name], but it does not work. Is there any solution available?

helper_method

module ProjectsHelper
  def form_for_projects_search_bar(condition1,condition2,condition3,&block)
   if condition1
     form_tag proposed_projects_path, method: :get, :html => {class: "form"}, &block

   elsif condition2
     form_tag completed_projects_path, method: :get, :html => {class: "form"}, &block

   elsif condition3
     form_tag projects_path, method: :get, :html => {class: "form"}, &block
   end

 end
end

form file

<%= form_for_projects_search_bar params[:proposed_projects].present?, params[:completed_projects].present?, params[:projects].present? do |form| %>
  <%= text_field_tag :term, params[:term],placeholder:"What are you looking for?", class: "search_field" %>
  <%= submit_tag 'Search', name: nil, class: "search_bar_button" %>
<% end %>

routes

projects_path   GET /projects(.:format)  projects#index
proposed_projects_path  GET /proposed_projects(.:format) projects#proposal
completed_projects_path GET /completed_projects(.:format) projects#completed

I want to check the condition based on the params name like proposed_projects, composed_projects, projects. If I am doing correct way in form.html.erb?.

If there is any other solution available?

2 Answers

0
RAJKUMAR PALANISAMY On Best Solutions
<%= form_for_projects_search_bar  params[:action]=="proposal", params[:action]=="completed", params[:action]=="progress" do  %>
  <%= text_field_tag :term, params[:term],placeholder:"What are you looking for?", class: "search_field" %>
<% end %>

differentiate each action like this...This may helps u..

0
CAmador On

Your helper doesn't help. If you want to DRY the form extract it to a partial (i.e. _form.html.erb) and set the path via locals:

_form.html.erb

<%= form_tag path, method: :get, :html => {class: "form"} do |form| %>
  <%= text_field_tag :term, params[:term],
                     placeholder: "What are you looking for?",
                     class: "search_field" %>
  <%= submit_tag 'Search', name: nil, class: "search_bar_button" %>
<% end %>

Then, render it in your view:

<% if params[:proposed_projects].present? %>
  <%= render 'form', path: proposed_projects_path %>
<% end %>
# add code for completed and in-progress

Once it is working you can write a helper for the ifs:

module ProjectsHelper
  def form_for_proposed_if(condition)
    # render form if condition
  end
end

view

<%= form_for_proposed_if params[:proposed_projects].present?

You'll end up with three helpers that can be DRY'd as well.