Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท LiveView

LiveView Events and Forms

Handle browser events in Phoenix LiveView: phx-click, phx-value, phx-change and phx-submit, to_form/2, changesets, live validation, debounce and errors.

A LiveView page becomes interactive when the browser tells the server what the user did. You attach binding attributes such as phx-click to elements, the LiveView JavaScript sends an event over the socket, and your handle_event/3 callback changes the assigns. Forms are the most important case: LiveView can validate input on every keystroke, using the same Ecto changeset rules you use when saving.

This lesson covers event bindings, how values travel with an event, and the full form cycle with to_form/2. As always, real Phoenix code is read-only here and the editors use a JavaScript stand-in for the validation flow. Changesets themselves are introduced in the Ecto chapter and in Ecto basics.

Event bindings

Attribute Fires when Sends
phx-click the element is clicked phx-value-* attributes
phx-change any input in a form changes all form fields
phx-submit the form is submitted all form fields
phx-blur / phx-focus an input loses or gets focus value, phx-value-*
phx-keydown / phx-keyup a key is pressed (use phx-key="Enter" to filter) key info
phx-window-keydown a key is pressed anywhere key info

The value of the attribute is the event name, and the matching function clause handles it:

HTML
<button phx-click="delete" phx-value-id={todo.id}>Delete</button>
ELIXIR
def handle_event("delete", %{"id" => id}, socket) do
  {:noreply, delete_todo(socket, String.to_integer(id))}
end

Every phx-value-NAME attribute becomes a key in the params map, and the value is always a string. Convert it yourself. Never trust the id blindly: the user can edit the HTML in DevTools, so check that the current user is allowed to delete that record, exactly as you would in a controller.

A handler can return a few shapes. The common ones are {:noreply, socket} and {:reply, map, socket} (the map goes back to a client hook, covered in LiveView hooks).

The form cycle

A LiveView form is driven by a form struct built from a changeset or a map. The cycle has four steps:

  1. mount/3 assigns an empty form with to_form/1.
  2. phx-change="validate" sends the current values on every change.
  3. validate builds a changeset, marks it with an action so errors show, and reassigns the form.
  4. phx-submit="save" saves, then either navigates away or shows errors.
ELIXIR
defmodule MyAppWeb.PostLive.New do
  use MyAppWeb, :live_view
  alias MyApp.Blog
  alias MyApp.Blog.Post

  def mount(_params, _session, socket) do
    changeset = Blog.change_post(%Post{})
    {:ok, assign(socket, form: to_form(changeset))}
  end

  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash}>
      <.form for={@form} id="post-form" phx-change="validate" phx-submit="save">
        <.input field={@form[:title]} label="Title" phx-debounce="300" />
        <.input field={@form[:body]} type="textarea" label="Body" />
        <.button phx-disable-with="Saving...">Publish</.button>
      </.form>
    </Layouts.app>
    """
  end

  def handle_event("validate", %{"post" => params}, socket) do
    changeset =
      %Post{}
      |> Blog.change_post(params)
      |> Map.put(:action, :validate)

    {:noreply, assign(socket, form: to_form(changeset))}
  end

  def handle_event("save", %{"post" => params}, socket) do
    case Blog.create_post(params) do
      {:ok, post} ->
        {:noreply,
         socket
         |> put_flash(:info, "Post created")
         |> push_navigate(to: ~p"/posts/#{post}")}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign(socket, form: to_form(changeset))}
    end
  end
end

Points worth reading twice:

  • <.input field={@form[:title]}> is a function component from core_components.ex. It reads the value and the error list for that field from the form, so you do not wire them by hand.
  • Map.put(:action, :validate) matters. Ecto only shows errors on a changeset that has an action. Without it, validation messages would not appear while typing.
  • phx-debounce="300" waits 300 ms after the last keystroke before sending. Use it on text inputs so the server is not hit for every letter. phx-throttle limits a rate instead.
  • phx-disable-with disables the button and swaps its text while the request is in flight, preventing double submits.
  • Give the form an id. LiveView uses ids to patch the DOM correctly, and tests use them to find the form.

Errors for a field are shown only after the user has interacted with it. In recent Phoenix versions <.input> hides errors for untouched fields, using the _unused_ marker the client sends with the params, so a fresh form does not start covered in red.

Modelling validation without Ecto

The next stand-in reproduces the cycle in plain JavaScript: a changeset-like object with validators and a "touched" set. Validation runs on every change, but errors are only shown for touched fields, as the real form does.

Node.js Live validation cycle (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Event routing

Under the hood, an event is a message {event name, params} delivered to the LiveView process, which pattern-matches it with function clauses. The following stand-in shows a todo list with phx-click events carrying phx-value-id strings, and why you convert them and check ownership.

Node.js Events with phx-value params (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If no clause matches, the LiveView process crashes with a FunctionClauseError and the client reconnects with a fresh mount. That crash-and-recover behaviour is a feature of the OTP model, but your users still lose unsaved state, so cover the events you render.

Practical tips

  • Use phx-change on the whole <form>, not on single inputs, so the server gets every field together.
  • Keep form state in the form struct. Do not copy typed values into separate assigns.
  • For a search box use phx-change with phx-debounce and update a list assign; there is no need for a submit button.
  • Add phx-trigger-action only if you must perform a real HTTP POST after validation, such as logging in with a session; the auth lessons use this.
  • Use push_event/3 to tell JavaScript hooks about server-side changes, covered later.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type are the values in a phx-value-id attribute when they arrive in handle_event/3?

    HTML attributes are text, so you must convert them yourself, for example with String.to_integer/1.
  2. 2. Why do you call Map.put(changeset, :action, :validate) in a validate handler?

    A changeset without an action is treated as not yet acted upon, so the form hides its errors.
  3. 3. What does phx-debounce=300 do on a text input?

    Debounce waits for the user to pause typing before sending the event, reducing server work.
  4. 4. What happens if no handle_event clause matches an incoming event?

    An unmatched pattern raises FunctionClauseError; the supervisor restarts the process and the client reconnects with fresh state.

Summary

  • Bindings like phx-click, phx-change and phx-submit send events; phx-value-* adds string params.
  • Forms are built with to_form/1 from a changeset and rendered with <.form> and <.input>.
  • Validate on phx-change, set the action so errors show, save on phx-submit.
  • Use phx-debounce for text fields and phx-disable-with to prevent double submits.
  • Always re-check authorization in the handler: params come from the browser.

Next: Streams, Navigation and JS Commands