Forms and Event Handlers in Elixir Phoenix Liveview

From ElixirBlocks
Revision as of 14:24, 19 June 2023 by Admin (talk | contribs)
Jump to: navigation, search

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 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"}