Chuyển đến nội dung

Bài 14 · Templates and Components

Forms, Changesets and to_form

Build Phoenix forms with to_form, the form component and input fields: show validation errors, protect with CSRF, handle uploads and nested inputs.

Forms connect your templates to your data. In Phoenix, a form is built from a changeset (Ecto's description of data plus validation errors) wrapped by to_form/1. The <.form> component emits the HTML, and <.input> shows each field with its errors. The same form works in controllers and in LiveView.

This lesson builds a new-post form end to end: the controller action, the template, error display, CSRF protection and a short look at file uploads. Changesets themselves are taught properly in changesets and validations; here you only need to know that a changeset carries a record's data and its errors.

Phoenix and Ecto code is read-only on this site. TryIts model the validation and rendering flow in JavaScript.

The new action

ELIXIR
def new(conn, _params) do
  changeset = Blog.Posts.change_post(%Blog.Posts.Post{})
  render(conn, :new, form: to_form(changeset))
end

def create(conn, %{"post" => post_params}) do
  case Blog.Posts.create_post(post_params) do
    {:ok, post} ->
      conn |> put_flash(:info, "Post created.") |> redirect(to: ~p"/posts/#{post}")

    {:error, %Ecto.Changeset{} = changeset} ->
      render(conn, :new, form: to_form(changeset))
  end
end

to_form(changeset) converts the changeset into a Phoenix.HTML.Form struct: field names, current values and errors. On failure you re-render the same form with the failed changeset, so users see their input and the messages.

The template

HEEX
<.header>New post</.header>

<.simple_form for={@form} action={~p"/posts"}>
  <.input field={@form[:title]} type="text" label="Title" />
  <.input field={@form[:body]} type="textarea" label="Body" />
  <.input field={@form[:published]} type="checkbox" label="Published" />
  <:actions>
    <.button>Save post</.button>
  </:actions>
</.simple_form>

@form[:title] gets one field: its name (post[title]), id, value and errors. The <.input> component picks the HTML element from type (text, email, password, textarea, select, checkbox, number, date...), and shows <p> error messages when the field has errors and was used (Phoenix hides errors for fields the user has not touched in LiveView, and shows all after a submit).

The name post[title] explains the params shape from the controller lesson: %{"post" => %{"title" => "..."}}. The prefix post comes from the schema name.

For an edit form, build the changeset from an existing record: Blog.Posts.change_post(post), then action={~p"/posts/#{@post}"} and the form helper adds _method=patch automatically when the data is persisted.

CSRF protection

The :browser pipeline includes protect_from_forgery. The <.form> component adds a hidden _csrf_token field, and Phoenix rejects POST, PUT, PATCH and DELETE requests whose token does not match the session. A forged form on another site lacks the token, so it fails. You get this protection for free; do not remove the plug, and do not turn the check off for browser routes.

Select, radio and other inputs

HEEX
<.input field={@form[:category]} type="select" label="Category"
        options={[{"Elixir", "elixir"}, {"Web", "web"}]} prompt="Choose one" />
<.input field={@form[:rating]} type="number" label="Rating" min="1" max="5" />

For options from the database, pass Enum.map(categories, &{&1.name, &1.id}).

Showing errors

Errors come from the changeset's validations:

ELIXIR
def changeset(post, attrs) do
  post
  |> cast(attrs, [:title, :body])
  |> validate_required([:title, :body])
  |> validate_length(:title, min: 3, max: 80)
end

The messages ("can't be blank", "should be at least 3 character(s)") are translated by CoreComponents.translate_error/1, which can use Gettext for other languages. You can also show a summary with @form.errors.

File uploads

Plain controllers receive uploads as %Plug.Upload{} structs (path, filename, content type) in params, and the form needs multipart:

HEEX
<.simple_form for={@form} action={~p"/avatars"} multipart>
  <.input field={@form[:file]} type="file" />
</.simple_form>
ELIXIR
def create(conn, %{"avatar" => %{"file" => %Plug.Upload{} = upload}}) do
  dest = Path.join("priv/uploads", Path.basename(upload.filename))
  File.cp!(upload.path, dest)
  ...
end

Never trust the client's filename: use Path.basename, generate your own names and validate size and type. LiveView has a richer built-in upload system.

Form handling, modeled

JS Validate and re-render a form with errors

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

No output.

The user's input survives re-rendering, and each field shows only its own messages.

CSRF token, modeled

JS A CSRF check

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

No output.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does to_form(changeset) produce?

    to_form wraps the changeset so templates can read @form[:field] values and errors.
  2. 2. What is the shape of params for a field named post[title]?

    Phoenix parses bracket names into nested maps with string keys.
  3. 3. What stops a forged cross-site form from changing data?

    The hidden _csrf_token must match the session; other sites cannot read it.
  4. 4. How should a failed create re-render the form?

    Rendering the same form with the failed changeset keeps input and shows errors.

Summary

  • Build a changeset, call to_form/1, and render with <.form>/<.simple_form> and <.input field={@form[:name]}>.
  • On failure re-render the form with the failed changeset; on success redirect.
  • The form component adds the CSRF token; keep protect_from_forgery enabled.
  • Uploads arrive as %Plug.Upload{} in multipart forms; sanitize names and check size and type.

Next: Ecto schemas and migrations

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.