How can I add a search form to app.html.heex that does a get request with the query param back to index#mount?
I’m trying to do similar as described in the Simple Search Form with Phoenix elixircast
but in trying all day, I’ve read I can’t use @conn in the .form for() attribute.
this is what I have currently, but it wants to got to a handle_event/3 call, instead of reloading the index page and passing the query param in mount.
<.form :let={f} for={} phx-submit="search">
<.input field={f[:query]} type="search" label="Search" />
<.button>Search</.button>
</.form>
This is my mount where I attempt to pass the query to the location schema to search.
def mount(params, _session, socket) do
# def handle_event("search", params, socket) do
dbg(params)
locations = Faclities.list_locations(params)
{:ok, stream(socket, :locations, Faclities.list_locations())}
end
any suggestions?
type or paste code here
I haven’t seen the ElixirCast but the reason handle_event
is getting called is because of the phx-submit="search"
. phx-submit
triggers the LiveView JS to submit the form. If you remove that and add method="post"
you should get the behaviour you want.
Hey there,
as @sodapopcan mentioned you can remove phx-submit
to trigger an action instead.
If you need a get
request you can simply define method="get"
. I would add action
explicetly.
So your form should look like this:
<.form :let={f} for={%{}} as={:search} action={~p"/"} method="get">
<.input field={f[:query]} placeholder="Search for something" />
</.form>
[/quote]
this way you will receive query params shaped like this: %{"search" => %{"query" => "something"}}
If you want to do validations before actually submitting the form you could use phx-trigger-action
:
def mount(_, _, socket) do
{:ok, assign(socket, :trigger_submit, false)}
end
def handle_event("submit", params, socket) do
if params_valid?(params) do
{:noreply, assign(socket, :trigger_submit, true)}
else
{:noreply, socket}
end
end
<.form :let={f} for={%{}} as={:search} action={~p"/"} phx-submit="submit" phx-trigger-action={@trigger_submit} method="get">
<.input field={f[:query]} placeholder="Search for something" />
</.form>
This way you would only actually trigger the action if all your validations were successful, which is really useful for immidiate feedback, but should be overkill in your case.
Greetings
1 Like
Thank you, this worked great!
Reading the Docs can be very confusing, I didn’t understand that I could add action and method attrs to the .form component for liveview.