<.form
for={@form}
phx-change="validate_strict"
phx-submit="save_strict"
>
<.radio_group
field={@form[:choice]}
class="radio-group"
items={[
%{value: "lorem", label: "Lorem ipsum dolor sit amet"},
%{value: "duis", label: "Duis dictum gravida odio ac pharetra?"},
%{value: "donec", label: "Donec condimentum ex mi"}
]}
on_value_change="choice_changed_strict"
>
<:label>Choose one</:label>
<:item_control><.heroicon name="hero-check" class="data-checked" /></:item_control>
<:error :let={msg}>
<.heroicon name="hero-exclamation-circle" class="icon" />
{msg}
</:error>
</.radio_group>
<.action type="submit" class="button button--accent">
Submit
</.action>
</.form>
defmodule MyAppWeb.RadioGroupFormLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
ecto_form =
%MyApp.Forms.RadioChoiceForm{}
|> MyApp.Forms.RadioChoiceForm.changeset_validate(%{})
|> Phoenix.Component.to_form(as: :radio_group_ecto, id: "radio-group-live-form-ecto")
{:ok, assign(socket, :ecto_form, ecto_form)}
end
def handle_event("validate", %{"radio_group_ecto" => params}, socket) do
changeset =
%MyApp.Forms.RadioChoiceForm{}
|> MyApp.Forms.RadioChoiceForm.changeset_validate(params)
|> Map.put(:action, :validate)
{:noreply,
assign(
socket,
:ecto_form,
Phoenix.Component.to_form(changeset,
action: :validate,
as: :radio_group_ecto,
id: "radio-group-live-form-ecto"
)
)}
end
def handle_event("save", %{"radio_group_ecto" => params}, socket) do
case MyApp.Forms.RadioChoiceForm.changeset_validate(%MyApp.Forms.RadioChoiceForm{}, params) do
%Ecto.Changeset{valid?: true} = changeset ->
_data = Ecto.Changeset.apply_changes(changeset)
{:noreply,
assign(
socket,
:ecto_form,
Phoenix.Component.to_form(
MyApp.Forms.RadioChoiceForm.changeset_validate(%MyApp.Forms.RadioChoiceForm{}, params),
as: :radio_group_ecto,
id: "radio-group-live-form-ecto"
)
)}
changeset ->
{:noreply,
assign(
socket,
:ecto_form,
Phoenix.Component.to_form(changeset,
action: :insert,
as: :radio_group_ecto,
id: "radio-group-live-form-ecto"
)
)}
end
end
end
defmodule MyApp.Forms.RadioChoiceForm do
use Ecto.Schema
import Ecto.Changeset
embedded_schema do
field :choice, :string
end
def changeset(form, attrs \\ %{}) do
form
|> cast(attrs, [:choice])
|> validate_required(:choice)
end
def changeset_validate(form, attrs \\ %{}) do
form
|> cast(attrs, [:choice])
|> validate_required([:choice])
end
end