phoenixframework / phoenix_html

Building blocks for working with HTML in Phoenix

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`FormData` for `Map` with atom keys

maennchen opened this issue · comments

v3.3.0 added support for Map FormData.

We already implemented something similar in our project, which now conflicts: https://github.com/jshmrtn/hygeia/blob/a3526482cd0ffad3b3d63d38f3673aab89011431/lib/hygeia_web/filter_data.ex

Unfortunately, we have a slight difference, which makes the migration quite hard for us: We used atom and not string keys for those forms. Example:

https://github.com/jshmrtn/hygeia/blob/a3526482cd0ffad3b3d63d38f3673aab89011431/lib/hygeia_web/live/row_live/apply.sface#L153

Is there a reason, why the new FormData implementation assumes string keys? Would you be open to a PR that allows both?

I was thinking something similar to this:

diff --git a/lib/phoenix_html/form_data.ex b/lib/phoenix_html/form_data.ex
index ff97f4c..5be47fe 100644
--- a/lib/phoenix_html/form_data.ex
+++ b/lib/phoenix_html/form_data.ex
@@ -167,6 +167,7 @@ defimpl Phoenix.HTML.FormData, for: [Plug.Conn, Atom, Map] do
     key = field_to_string(field)
 
     case params do
+      %{^field => value} -> value
       %{^key => value} -> value
       %{} -> Map.get(data, field)
     end

So the issue is that we treat map as parameters, not as data, and parameters always have string keys. So I would be worried about allowing mixed lookup for now. What we could do is to look at the map and see if it has string or atom keys and decide accordingly, but I am not sure.

look at the map and see if it has string or atom keys

Kindof like ecto params. I could also open a PR for that.

The use case we had in mind when building this was a lot of tiny independent forms for which we built the maps they operate on manually. (And used atom keys for that.)

If that is not something you would like to support, I would at least add a warning if atom keys are passed instead of strings as to not confuse people why passing an atom key for an atom map does not yield a result.

The warning is already on main. :)

Let's keep this as is for now, you can keep your code by wrapping it in another data structure. But if there is more demand (or more confusion), we can relax it to work with both atom and string keys.

@josevalim Hm, you're right, there is a warning. In that case I'll have to find out why it did not trigger.

I might open a follow up ticket depending on the outcome.

Sounds good!