...

/

Generate a Form for a Single Schema

Generate a Form for a Single Schema

Learn how to generate a form for a single schema.

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.

Press + to interact
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.

Press + to interact
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 ...