Generate a Form for a Single Schema
Learn how to generate a form for a single schema.
We'll cover the following...
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 doimport Ecto.Changesetuse Ecto.Schemaschema "users" dofield :name, :stringfield :age, :integerenddef changeset(user, params) douser|> cast(params, [:name, :age])|> validate_required(:name)|> validate_number(:age, greater_than: 0,message: "you are not yet born")endend
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) dochangeset = User.changeset(%User{}, %{})render(conn, changeset: changeset)end
Set up the form
Now we’re ready to set up the form. To ...