Forms and Event Handlers in Elixir Phoenix Liveview: Difference between revisions
(Created page with "{{In_progress}} {{Phoenix-Installation-Required}} To begin, create a new basic working LiveView Page. Follow the tutorial here and then come back to this page when you are done. <source> defmodule AppWeb.PageLive do use AppWeb, :live_view def mount(_params, _session, socket) do {:ok, socket} end def render(assigns) do ~...") |
No edit summary |
||
Line 85: | Line 85: | ||
</form> | </form> | ||
</source> | </source> | ||
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 in a map. |
Revision as of 14:21, 19 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.
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 event handler listens and responds to an event named "send".
def handle_event("send", params, socket) do # "send" is the event listened for IO.inspect(params) {:noreply, socket} end
Form submission invokes an event named "send" and it does so with this line of code:
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 in a map.