Components
Forms (v2)
Forms (v2)
These components use the new `to_form/2` functionality
In Phoenix 1.7, forms were given a new data structure. For more information see the release notes or the latest form docs.
v1 way (pre Phoenix 1.7):
# In your LiveView
def mount(_params, _session, socket) do
changeset = Blog.changeset(%Post{})
socket = assign(socket, changeset: changeset)
{:ok, socket}
end
<.form :let={f} as={:user} for={@changeset} phx-submit="on_submit">
<.form_field type="text_input" form={f} field={:title} />
<.form_field
form={f}
field={:state}
type="select"
options={[{"Draft", "draft"}, {"Published", "published"}]}
/>
<.button type="submit" label="Submit" />
</.form>
v2 way (Phoenix 1.7):
# In your LiveView
def mount(_params, _session, socket) do
changeset = Blog.changeset(%Post{})
socket = assign(socket, form: to_form(changeset))
{:ok, socket}
end
<.form for={@form} phx-submit="on_submit">
<.field field={@form[:title]} />
<.field
field={@form[:state]}
type="select"
options={[{"Draft", "draft"}, {"Published", "published"}]}
/>
<.button type="submit" label="Submit" />
</.form>
Go here for the v1 docs. There is no rush to upgrade to v2. It only matters if you’d like to utilize the Live View optimizations around forms (see the links above for more information).
All fields example
Here’s an example of all the fields in one form. This is handy as a quick reference.