Skip to content

Commit

Permalink
Set action in child form, closes #173
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Mar 7, 2024
1 parent 5e4b297 commit 21eda29
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/phoenix_ecto/html.ex
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ if Code.ensure_loaded?(Phoenix.HTML) do

%Phoenix.HTML.Form{
source: changeset,
action: parent_action,
impl: __MODULE__,
id: id,
name: name,
Expand Down Expand Up @@ -93,6 +94,7 @@ if Code.ensure_loaded?(Phoenix.HTML) do
%Phoenix.HTML.Form{
source: changeset,
impl: __MODULE__,
action: parent_action,
id: id <> "_" <> index_string,
name: name <> "[" <> index_string <> "]",
index: index,
Expand Down
28 changes: 27 additions & 1 deletion test/phoenix_ecto/inputs_for_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,17 @@ defmodule PhoenixEcto.InputsForTest do

import Ecto.Changeset

defp to_inputs_form(changeset, field, opts \\ []) do
defp to_inputs_form(changeset_or_form, field, opts \\ [])

defp to_inputs_form(%Ecto.Changeset{} = changeset, field, opts) do
form = Phoenix.HTML.FormData.to_form(changeset, [])
Phoenix.HTML.FormData.to_form(changeset, form, field, opts)
end

defp to_inputs_form(%Phoenix.HTML.Form{} = form, field, opts) do
Phoenix.HTML.FormData.to_form(form.source, form, field, opts)
end

## has_one

test "has one: simple" do
Expand Down Expand Up @@ -619,4 +625,24 @@ defmodule PhoenixEcto.InputsForTest do

[] = to_inputs_form(changeset, :permalinks)
end

## Nesting

test "action tracking with nesting" do
changeset =
%User{comment: %Comment{body: "data", child_comments: [%Comment{body: "child"}]}}
|> cast(%{}, ~w()a)
|> cast_assoc(:comment)

f = Phoenix.HTML.FormData.to_form(changeset, action: :insert)
assert f.action == :insert

[f] = to_inputs_form(f, :comment)
assert f.action == :insert
assert f.source.data.body == "data"

[f] = to_inputs_form(f, :child_comments)
assert f.action == :insert
assert f.source.data.body == "child"
end
end
2 changes: 2 additions & 0 deletions test/test_helper.exs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ defmodule Comment do
schema "comments" do
field :body
field :position, :integer
has_many :child_comments, Comment
end

def changeset(comment, params) do
Expand All @@ -30,6 +31,7 @@ defmodule Comment do
|> cast(params, ~w(body)a)
|> validate_required(:body)
|> validate_length(:body, min: 3)
|> cast_assoc(:child_comments)
end

def custom_changeset(comment, params, required_length) do
Expand Down

0 comments on commit 21eda29

Please sign in to comment.