Skip to content

Commit

Permalink
Allow keyword list options to use nil as key and/or value
Browse files Browse the repository at this point in the history
  • Loading branch information
LostKobrakai committed Jan 22, 2025
1 parent df2a3f6 commit 5ce67bf
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
13 changes: 7 additions & 6 deletions lib/phoenix_html/form.ex
Original file line number Diff line number Diff line change
Expand Up @@ -334,17 +334,18 @@ defmodule Phoenix.HTML.Form do
[acc | option(option_key, option_value, [], selected_values)]

options, acc when is_list(options) ->
{option_key, options} = Keyword.pop(options, :key)

option_key ||
if not Keyword.has_key?(options, :key) do
raise ArgumentError,
"expected :key key when building <option> from keyword list: #{inspect(options)}"
end

{option_value, options} = Keyword.pop(options, :value)

option_value ||
if not Keyword.has_key?(options, :value) do
raise ArgumentError,
"expected :value key when building <option> from keyword list: #{inspect(options)}"
end

{option_key, options} = Keyword.pop(options, :key)
{option_value, options} = Keyword.pop(options, :value)

[acc | option(option_key, option_value, options, selected_values)]

Expand Down
11 changes: 7 additions & 4 deletions test/phoenix_html/form_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,10 @@ defmodule Phoenix.HTML.FormTest do

describe "options_for_select/2" do
test "simple" do
assert options_for_select(~w(value novalue), "novalue") |> safe_to_string() ==
assert options_for_select(["value", "novalue", nil], "novalue") |> safe_to_string() ==
~s(<option value="value">value</option>) <>
~s(<option selected value="novalue">novalue</option>)
~s(<option selected value="novalue">novalue</option>) <>
~s(<option value=""></option>)

assert options_for_select(["value", :hr, "novalue"], "novalue") |> safe_to_string() ==
~s(<option value="value">value</option>) <>
Expand All @@ -261,14 +262,16 @@ defmodule Phoenix.HTML.FormTest do
[
[value: "value", key: "Value", disabled: true],
:hr,
[value: "novalue", key: "No Value"]
[value: "novalue", key: "No Value"],
[value: nil, key: nil]
],
"novalue"
)
|> safe_to_string() ==
~s(<option disabled value="value">Value</option>) <>
~s(<hr/>) <>
~s(<option selected value="novalue">No Value</option>)
~s(<option selected value="novalue">No Value</option>) <>
~s(<option value=""></option>)

assert options_for_select(~w(value novalue), ["value", "novalue"]) |> safe_to_string() ==
~s(<option selected value="value">value</option>) <>
Expand Down

0 comments on commit 5ce67bf

Please sign in to comment.