Forms and Event Handlers in Elixir Phoenix Liveview: Difference between revisions
No edit summary |
No edit summary |
||
Line 58: | Line 58: | ||
The | The handle_event() function listens and responds to an event defined as its first argument. In this case, it is named "send". | ||
<source> | <source> | ||
Line 69: | Line 69: | ||
</source> | </source> | ||
When the form below is submitted, it invoke the handle_event function above that has the same string associated with it. In this case it's "send". | |||
<source> | <source> |
Revision as of 18:58, 20 June 2023
This page is in progress
Installing Phoenix
This article assumes that you have installed the Phoenix web framework and all its dependencies correctly without errors. If you have not installed the Phoenix web framework please view the documentation here
To begin, create a new basic working LiveView Page.
If you need to, follow the tutorial here and then come back to this page when you are done.
defmodule AppWeb.PageLive do use AppWeb, :live_view def mount(_params, _session, socket) do {:ok, socket} end def render(assigns) do ~H""" Hello World! YAY """ end end
Change the code above to contain a form and an event_handler. The code below reflects how this should look.
use AppWeb, :live_view def mount(_params, _session, socket) do {:ok, socket} end def handle_event("send", params, socket) do IO.inspect(params) {:noreply, socket} end def render(assigns) do ~H""" <div> <h1>connection Send</h1> <form phx-submit="send"> <input type="text" name="text-field" /> <input type="text" name="another-filed" /> <button type="submit">Send</button> </form> </div> """ end
The handle_event() function listens and responds to an event defined as its first argument. In this case, it is named "send".
def handle_event("send", params, socket) do # "send" is the name of the event listened for IO.inspect(params) {:noreply, socket} end
When the form below is submitted, it invoke the handle_event function above that has the same string associated with it. In this case it's "send".
phx-submit="send"
It is placed here:
<form phx-submit="send"> <input type="text" name="text-field" /> <input type="text" name="another-filed" /> <button type="submit">Send</button> </form>
When you submit the form, the contents of handle_event run. In this case, IO.inspect is used to view params. Params contain the form field contents as a map data structure.
The keys of the map are the input field names and the contents of each field is assigned to its respective key.
%{"another-filed" => "the data", "text-field" => "more data"}