<.form
for={@strict_form}
phx-change="validate_strict"
phx-submit="save_strict"
>
<.combobox
field={@strict_form[:country]}
class="combobox"
placeholder="Country"
items={Corex.List.new([
%{label: "France", value: "fra"},
%{label: "Belgium", value: "bel"},
%{label: "Germany", value: "deu"},
%{label: "Netherlands", value: "nld"},
%{label: "Switzerland", value: "che"},
%{label: "Austria", value: "aut"}
])}
>
<:label>Country</:label>
<:empty>No results</:empty>
<:trigger><.heroicon name="hero-chevron-down" /></:trigger>
<:error :let={msg}>
<.heroicon name="hero-exclamation-circle" class="icon" />
{msg}
</:error>
</.combobox>
<.action type="submit" class="button button--accent">Submit</.action>
</.form>
defmodule MyAppWeb.ComboboxFormLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
ecto_form =
%MyApp.Forms.Travel{}
|> MyApp.Forms.Travel.changeset_validate(%{})
|> Phoenix.Component.to_form(as: :combobox_ecto, id: "combobox-live-form-ecto")
{:ok, assign(socket, :ecto_form, ecto_form)}
end
def handle_event("validate", %{"combobox_ecto" => params}, socket) do
changeset =
%MyApp.Forms.Travel{}
|> MyApp.Forms.Travel.changeset_validate(params)
|> Map.put(:action, :validate)
{:noreply,
assign(
socket,
:ecto_form,
Phoenix.Component.to_form(changeset,
action: :validate,
as: :combobox_ecto,
id: "combobox-live-form-ecto"
)
)}
end
def handle_event("save", %{"combobox_ecto" => params}, socket) do
case MyApp.Forms.Travel.changeset_validate(%MyApp.Forms.Travel{}, params) do
%Ecto.Changeset{valid?: true} = changeset ->
_data = Ecto.Changeset.apply_changes(changeset)
{:noreply,
assign(
socket,
:ecto_form,
Phoenix.Component.to_form(
MyApp.Forms.Travel.changeset_validate(%MyApp.Forms.Travel{}, params),
as: :combobox_ecto,
id: "combobox-live-form-ecto"
)
)}
changeset ->
{:noreply,
assign(
socket,
:ecto_form,
Phoenix.Component.to_form(changeset,
action: :insert,
as: :combobox_ecto,
id: "combobox-live-form-ecto"
)
)}
end
end
end
defmodule MyApp.Forms.Travel do
use Ecto.Schema
import Ecto.Changeset
embedded_schema do
field :country, :string
end
def changeset(form, attrs \\ %{}) do
form
|> cast(attrs, [:country])
|> validate_required([:country])
end
def changeset_validate(form, attrs \\ %{}) do
form
|> cast(attrs, [:country])
|> validate_required([:country], message: "can't be blank")
end
end