Skip to content

Commit

Permalink
Use changeset action if no action passed
Browse files Browse the repository at this point in the history
  • Loading branch information
chrismccord committed Feb 6, 2024
1 parent 8ef8ee8 commit a9e1a3d
Showing 1 changed file with 9 additions and 12 deletions.
21 changes: 9 additions & 12 deletions lib/phoenix_ecto/html.ex
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
if Code.ensure_loaded?(Phoenix.HTML) do
defimpl Phoenix.HTML.FormData, for: Ecto.Changeset do
def to_form(changeset, opts) do
{action, changeset} =
case Keyword.fetch(opts, :action) do
{:ok, action} -> {action, Map.put(changeset, :action, action)}
:error -> {nil, changeset}
end
{action, opts} = Keyword.pop_lazy(opts, :action, fn -> changeset.action end)
changeset = Map.put(changeset, :action, action)

%{params: params, data: data} = changeset
{name, opts} = Keyword.pop(opts, :as)
Expand All @@ -19,15 +16,15 @@ if Code.ensure_loaded?(Phoenix.HTML) do
id: id,
action: action,
name: name,
errors: form_for_errors(changeset),
errors: form_for_errors(changeset, action),
data: data,
params: params || %{},
hidden: form_for_hidden(data),
options: Keyword.put_new(opts, :method, form_for_method(data))
}
end

def to_form(%{action: parent_action} = source, form, field, opts) do
def to_form(source, %{action: parent_action} = form, field, opts) do
if Keyword.has_key?(opts, :default) do
raise ArgumentError,
":default is not supported on inputs_for with changesets. " <>
Expand Down Expand Up @@ -65,7 +62,7 @@ if Code.ensure_loaded?(Phoenix.HTML) do
impl: __MODULE__,
id: id,
name: name,
errors: form_for_errors(changeset),
errors: form_for_errors(changeset, parent_action),
data: data,
params: params || %{},
hidden: form_for_hidden(data),
Expand Down Expand Up @@ -99,7 +96,7 @@ if Code.ensure_loaded?(Phoenix.HTML) do
id: id <> "_" <> index_string,
name: name <> "[" <> index_string <> "]",
index: index,
errors: form_for_errors(changeset),
errors: form_for_errors(changeset, parent_action),
data: data,
params: params || %{},
hidden: form_for_hidden(data),
Expand Down Expand Up @@ -309,9 +306,9 @@ if Code.ensure_loaded?(Phoenix.HTML) do
raise ArgumentError, "expected #{what} to be a map/struct, got: #{inspect(value)}"
end

defp form_for_errors(%{action: nil}), do: []
defp form_for_errors(%{action: :ignore}), do: []
defp form_for_errors(%{errors: errors}), do: errors
defp form_for_errors(%Ecto.Changeset{}, nil = _action), do: []
defp form_for_errors(%Ecto.Changeset{}, :ignore = _action), do: []
defp form_for_errors(%Ecto.Changeset{errors: errors}, _action), do: errors

defp form_for_hidden(%{__struct__: module} = data) do
module.__schema__(:primary_key)
Expand Down

0 comments on commit a9e1a3d

Please sign in to comment.