Certainly! Phoenix LiveView is a powerful library in the Elixir ecosystem that allows you to build real-time, interactive web applications without writing much JavaScript. Forms are a crucial part of web development, and LiveView makes handling them intuitive and efficient.
Below, I'll walk you through the basics of forms in Phoenix LiveView, covering key concepts, steps, and examples to help you get started.
1. What Are LiveView Forms?
LiveView forms allow you to create dynamic, interactive forms that update in real time without requiring a full page reload. They leverage server-side rendering and WebSockets to provide a seamless user experience.
Key features:
- Real-time validation and feedback.
- Server-side state management.
- Minimal JavaScript required.
- Built-in support for handling form submissions and changes.
2. Setting Up a LiveView Form
Step 1: Generate a LiveView
If you haven't already created a LiveView, you can generate one using the mix task:
mix phx.gen.live ContextName ResourceName field:type field:type
For example:
mix phx.gen.live Blog Post title:string body:text
This will generate:
- A context module (
Blog).
- A schema (
Post).
- Migration files.
- LiveView templates and modules.
Run the migration to create the database table:
mix ecto.migrate
Step 2: Define the Form in the LiveView Template
In your .html.heex file (e.g., lib/my_app_web/live/post_live/form.html.heex), define the form using the Phoenix.HTML.Form helpers:
<%= f = form_for @changeset, "#", [phx_change: :validate, phx_submit: :save] %>
<div>
<%= label f, :title %>
<%= text_input f, :title %>
<%= error_tag f, :title %>
</div>
<div>
<%= label f, :body %>
<%= textarea f, :body %>
<%= error_tag f, :body %>
</div>
<div>
<%= submit "Save" %>
</div>
</form>
@changeset: The changeset containing the form data and validation errors.
phx_change: Triggers a validate event on the server when the form changes.
phx_submit: Triggers a save event on the server when the form is submitted.
3. Handling Form Events in the LiveView Module
In your LiveView module (e.g., lib/my_app_web/live/post_live/form.ex), handle the validate and save events:
defmodule MyAppWeb.PostLive.Form do
use MyAppWeb, :live_view
alias MyApp.Blog
alias MyApp.Blog.Post
def mount(_params, _session, socket) do
{:ok, assign(socket, changeset: Blog.change_post(%Post{}))}
end
def handle_event("validate", %{"post" => post_params}, socket) do
changeset =
%Post{}
|> Blog.change_post(post_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, changeset: changeset)}
end
def handle_event("save", %{"post" => post_params}, socket) do
case Blog.create_post(post_params) do
{:ok, _post} ->
{:noreply,
socket
|> put_flash(:info, "Post created successfully")
|> push_redirect(to: "/posts")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
end
Explanation:
-
mount/3:
- Initializes the socket with an empty changeset for the form.
Blog.change_post/1 generates a changeset for the Post schema.
-
handle_event/3 for "validate":
- Called when the form changes.
- Updates the changeset with the new parameters and sets the action to
:validate.
- This allows you to display validation errors in real time.
-
handle_event/3 for "save":
- Called when the form is submitted.
- Attempts to create a new post using
Blog.create_post/1.
- If successful, redirects the user to the posts index page.
- If there are validation errors, updates the changeset to display them.
4. Displaying Validation Errors
To display validation errors, define an error_tag helper in your lib/my_app_web/core_components.ex file:
def error_tag(form, field) do
if error = Enum.find_value(form.errors, fn {key, value} -> key == field && value end) do
content_tag(:span, translate_error(error), class: "help-block")
end
end
defp translate_error({msg, opts}) do
Enum.reduce(opts, msg, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end
This helper will render error messages below the corresponding form fields.
5. Testing the Form
-
Start your Phoenix server:
mix phx.server
-
Navigate to the form page (e.g., /posts/new).
-
Test the form by entering invalid data (e.g., leaving required fields blank) and observe the real-time validation errors.
-
Submit valid data and verify that the post is created and you are redirected.
6. Additional Tips
- Preloading Data: If your form depends on preloaded data (e.g., dropdown options), fetch it in the
mount/3 function and assign it to the socket.
- Nested Forms: For nested forms, use
inputs_for to handle associations.
- File Uploads: Use
Phoenix.LiveView.Upload for handling file uploads in LiveView forms.
Conclusion
By following the steps above, you can create dynamic, real-time forms in Phoenix LiveView with minimal effort. The key is to leverage the power of Elixir's changesets for validation and LiveView's event handling for interactivity.
If you have any specific questions or need further clarification, feel free to ask!