Rbtz.CredoChecks.Refactor.PreferToFormInTemplates
(rbtz_credo_checks v0.1.0)
Copy Markdown
View Source
Basics
This check is disabled by default.
Learn how to enable it via .credo.exs.
This check has a base priority of normal and works with any version of Elixir.
Explanation
Forbids passing a raw @changeset to a <form> / <.form> in HEEx —
always wrap the changeset with to_form/2 first and pass the resulting
@form.
Phoenix.Component.to_form/2 builds a Phoenix.HTML.Form struct that
knows how to render input names, attach errors per-field, derive a stable
id, and round-trip values through phx-change. Passing the changeset
directly skips all of that: errors won't appear next to the right inputs,
<.input field={...}> cannot resolve the field name, and form recovery
breaks on reconnect.
The check inspects every ~H sigil and every .heex template referenced
via embed_templates. It tracks when the cursor is inside a
<form>/<.form> element and flags any @changeset reference in that
scope.
Bad
<.form for={@changeset} phx-submit="save">
<.input field={@changeset[:name]} />
</.form>Good
# In the LiveView:
{:ok, assign(socket, :form, to_form(changeset))}
# In the template:
<.form for={@form} phx-submit="save">
<.input field={@form[:name]} />
</.form>Check-Specific Parameters
There are no specific parameters for this check.
General Parameters
Like with all checks, general params can be applied.
Parameters can be configured via the .credo.exs config file.