3
votes

I'm trying to make a simple search form to filter my list of resources. I've made a form like this, but it's not placing q in the url as a query param like I would expect with method: :get

<%= form_for @conn, post_path(@conn, :index), [as: :search, method: :get], fn f -> %>
  <%= text_input f, :q, placeholder: "Search by title, content, etc." %>
<% end %>

When I submit this form with "term" as the search term, it results in search%5Bq%5D=term being placed in the url (the url encoded version of the name of the q field.) I expected just q=term. Am I incorrect in expecting that? What's the proper way to do a simple search form?

1
You can either use hexdocs.pm/phoenix_html/Phoenix.HTML.Tag.html#form_tag/2 which would not generate input names for you or simple override the text_input name attribute set it to qNoDisplayName
Awesome, that worked too. I decided to upgrade to phoenix_html 2.10.5 though.denvaar

1 Answers

4
votes

All fields in the form are wrapped by the argument as, e.g. q with as: :search becomes search[q]. You can either keep doing this and extract this variable in the controller like this:

def index(conn, %{"search" => %{"q" => q}}) do
  ...
end

Or, if you want the field to be just q, you can upgrade to v2.10.5 of phoenix_html and remove the as argument. This argument was made optional just 5 days ago.