Skip to content
TheChatArchiveThe Chat Archive
Metallama-4-maverick-17b-128e-instruct· MetaHugging Face LMArena Human Preference 140K

Teach me Phoenix Liveview forms basics

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen-max-2025-01-25’s answer.
  1. User

    Teach me Phoenix Liveview forms basics

  2. Meta Assistant

    Phoenix LiveView is a powerful tool for building real-time web applications with Elixir and Phoenix. Handling forms is a crucial aspect of web development, and LiveView makes it relatively straightforward with its built-in features. Let's dive into the basics of handling forms with Phoenix LiveView.

    Step 1: Setting Up Your LiveView

    First, ensure you have Phoenix and LiveView set up in your project. If you're starting from scratch, you can create a new Phoenix project with LiveView by running:

    mix phx.new my_app --live
    

    Navigate into your project directory and follow the instructions provided by the mix phx.new task to set up your application.

    Step 2: Creating a LiveView

    Generate a LiveView for handling your form. For example, let's say you're creating a simple user registration form:

    mix phx.gen.live Accounts User users name:string email:string
    

    However, for this example, we'll manually create a simple LiveView for a fictional User schema without using the generator.

    Step 3: Basic Form Handling

    Let's create a simple LiveView that handles a form for a User struct. First, define a simple User struct in lib/my_app/accounts/user.ex:

    defmodule MyApp.Accounts.User do
      use Ecto.Schema
    
      @derive {Jason.Encoder, only: [:name, :email]}
      schema "users" do
        field :name, :string
        field :email, :string
    
        timestamps()
      end
    
      def changeset(user, params) do
        user
        |> cast(params, [:name, :email])
        |> validate_required([:name, :email])
      end
    end
    

    Step 4: Creating the LiveView

    Create a new LiveView in lib/my_app_web/live/user_live.ex:

    defmodule MyAppWeb.UserLive do
      use MyAppWeb, :live_view
    
      alias MyApp.Accounts.User
    
      def mount(_params, _session, socket) do
        {:ok, assign(socket, user: %User{}, changeset: User.changeset(%User{}, %{}) )}
      end
    
      def render(assigns), do: Phoenix.View.render(MyAppWeb.UserView, "form.html", assigns)
    
      def handle_event("validate", %{"user" => user_params}, socket) do
        changeset = User.changeset(socket.assigns.user, user_params)
        {:noreply, assign(socket, changeset: changeset)}
      end
    
      def handle_event("save", %{"user" => user_params}, socket) do
        # Here you would typically insert the user into the database
        # For now, we'll just print the params
        IO.inspect(user_params)
        {:noreply, socket}
      end
    end
    

    Step 5: Creating the Form

    Create a view template for the form in lib/my_app_web/templates/user/form.html.heex:

    <h1>User Form</h1>
    
    <.form let={f} for={@changeset} phx-change="validate" phx-submit="save">
      <%= label f, :name %>
      <%= text_input f, :name %>
      <%= error_tag f, :name %>
    
      <%= label f, :email %>
      <%= text_input f, :email %>
      <%= error_tag f, :email %>
    
      <%= submit "Save" %>
    </.form>
    

    Step 6: Routing

    Add a route for your LiveView in lib/my_app_web/router.ex:

    scope "/", MyAppWeb do
      pipe_through [:browser]
    
      live "/users/new", UserLive, :new
    end
    

    Step 7: Running Your Application

    Start your Phoenix server:

    mix phx.server
    

    Visit http://localhost:4000/users/new in your browser to see the form in action. As you fill out the form, LiveView will validate the input in real-time due to the phx-change="validate" attribute on the form. When you submit the form, the phx-submit="save" event is triggered, and the form data is inspected in the console.

    This is a basic overview of handling forms with Phoenix LiveView. You can expand upon this by adding more complex validation, handling errors, and integrating with your database to persist the form data.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.