Search⌘ K
AI Features

Generate a Form for a Single Schema

Explore how to generate a form for a single schema using Ecto changesets within Phoenix. Learn to define a user schema, set up a controller action, build a form with form_for, and process form submissions to create user records. Understand changeset validation and error handling to create dynamic, user-friendly forms.

Set up a simple schema

Let’s set up a simple User schema as a starting point. We’ll define fields for name and age and add a changeset function that will cast and validate incoming parameters.

Elixir
defmodule MyApp.User do
import Ecto.Changeset
use Ecto.Schema
schema "users" do
field :name, :string
field :age, :integer
end
def changeset(user, params) do
user
|> cast(params, [:name, :age])
|> validate_required(:name)
|> validate_number(:age, greater_than: 0,
message: "you are not yet born")
end
end

Define new action on the controller

Next, we’ll need a controller. When we invoke the new action on the controller, we want to return a new, empty changeset for a User, as shown below.

Elixir
def new(conn, _params) do
changeset = User.changeset(%User{}, %{})
render(conn, changeset: changeset)
end

Set up the form

Now we’re ready to set up the form. To build forms from ...