Skip to content

Commit c11a9e3

Browse files
committed
Implement Access for form fields
1 parent 71430c1 commit c11a9e3

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/phoenix_html/form_field.ex

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ defmodule Phoenix.HTML.FormField do
1111
* `:name` - the `name` to be used as form input as a string
1212
* `:value` - the value for the input
1313
14+
This struct also implements the `Access` behaviour,
15+
but raises if you try to access a field that is not defined.
1416
"""
1517
@type t :: %__MODULE__{
1618
id: String.t(),
@@ -23,4 +25,21 @@ defmodule Phoenix.HTML.FormField do
2325

2426
@enforce_keys [:id, :name, :errors, :field, :form, :value]
2527
defstruct [:id, :name, :errors, :field, :form, :value]
28+
29+
@behaviour Access
30+
31+
@impl true
32+
def fetch(struct, key) do
33+
{:ok, Map.fetch!(struct, key)}
34+
end
35+
36+
@impl true
37+
def get_and_update(struct, key, fun) do
38+
Map.get_and_update!(struct, key, fun)
39+
end
40+
41+
@impl true
42+
def pop(struct, _key) do
43+
raise ArgumentError, "cannot pop keys from #{inspect(struct)}"
44+
end
2645
end

test/phoenix_html/form_test.exs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,9 @@ defmodule Phoenix.HTML.FormTest do
168168
name: "atom",
169169
errors: ["oops"]
170170
}
171+
172+
assert form[:key][:id] == "key"
173+
assert form[:atom][:value] == "data"
171174
end
172175

173176
test "with name and atom keys" do
@@ -193,6 +196,9 @@ defmodule Phoenix.HTML.FormTest do
193196
name: "search[atom]",
194197
errors: ["oops"]
195198
}
199+
200+
assert form[:key][:id] == "search_key"
201+
assert form[:atom][:value] == "data"
196202
end
197203

198204
test "without name and string keys" do
@@ -218,6 +224,9 @@ defmodule Phoenix.HTML.FormTest do
218224
name: "string",
219225
errors: ["oops"]
220226
}
227+
228+
assert form["key"][:id] == "key"
229+
assert form["string"][:value] == "data"
221230
end
222231

223232
test "with name and string keys" do
@@ -243,6 +252,9 @@ defmodule Phoenix.HTML.FormTest do
243252
name: "search[string]",
244253
errors: ["oops"]
245254
}
255+
256+
assert form["key"][:id] == "search_key"
257+
assert form["string"][:value] == "data"
246258
end
247259
end
248260

0 commit comments

Comments
 (0)