Forms and Event Handlers in Elixir Phoenix Liveview: Difference between revisions

From ElixirBlocks
Jump to: navigation, search
No edit summary
No edit summary
Line 58: Line 58:




The event handler listens and responds to an event named "send".
The event handler listens and responds to an event defined on its first argument. In this case it is named "send".  


<source>
<source>
   def handle_event("send", params, socket) do  # "send" is the event listened for
   def handle_event("send", params, socket) do  # "send" is the name of the event listened for
     IO.inspect(params)
     IO.inspect(params)



Revision as of 18:53, 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.

Inf 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 event handler listens and responds to an event defined on 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

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