Renders a form field including input, label, errors, and description.
A Phoenix.HTML.FormField
may be passed as argument,
which is used to retrieve the input name, id, and values.
Otherwise all attributes may be passed explicitly.
In addition to all HTML input types, the following type values are also supported:
"select"
"checkbox-group"
"radio-group"
"switch"
Note that the class
attribute is applied to the outer container, while
the rest
global attribute is applied to the <input>
element.
To translate field errors using Gettext, set the gettext_module
option
when building the component:
build_field(gettext_module: MyApp.Gettext)
The component does not provide an attribute to modify label positioning directly. Instead, label positioning should be handled with CSS. If your application requires different label positions, such as horizontal and vertical layouts, it is recommended to add a modifier class to the form.
For example, the default style could position labels above inputs. To place
labels to the left of the inputs in a horizontal form layout, you can add an
is-horizontal
class to the form:
<.form class="is-horizontal">
<!-- inputs -->
</.form>
Then, in your CSS, apply the necessary styles to the .field
class within
forms having the is-horizontal
class:
form.is-horizontal .field {
// styles to position label left of the input
}
The component has a hide_label
attribute to visually hide labels while still
making them accessible to screen readers. If all labels within a form need to
be visually hidden, it may be more convenient to define a
.has-visually-hidden-labels
modifier class for the <form>
.
<.form class="has-visually-hidden-labels">
<!-- inputs -->
</.form>
Ensure to take checkbox and radio labels into consideration when writing the CSS styles.
<.field field={@form[:name]} />
<.field field={@form[:email]} type="email" />
The radio-group
and checkbox-group
types allow you to easily render groups
of radio buttons or checkboxes with a single component invocation. The
options
attribute is required for these types and has the same format as
the options for the select
type, except that options may not be nested.
<.field
field={@form[:email]}
type="checkbox-group"
label="Cuisine"
options={[
{"Mexican", "mexican"},
{"Japanese", "japanese"},
{"Libanese", "libanese"}
]}
/>
Note that the checkbox-group
type renders an additional hidden input with
an empty value before the checkboxes. This ensures that a value exists in case
all checkboxes are unchecked. Consequently, the resulting list value includes
an extra empty string. While Ecto.Changeset.cast/3
filters out empty strings
in array fields by default, you may need to handle the additional empty string
manual in other contexts.