Can I get a list of items on form submission instead of a map?

I get a list that looks like this:

"items" => %{
  "0" => %{"value" => "a"},
  "1" => %{"value" => "b"}
}

when I submit the form. but what I want to get is a list not a map like:

"items" => [
  %{"value" => "a"},
  %{"value" => "b"}
]

Is there a way to get that result?

if not what is the best way to convert this map into a list?

You should not do that unless these form fields really represent a list. (if not: give the fields some proper names)
But if you really want to

items
|> Enum.map(fn {k, v} -> {String.to_integer(k), v} end)
|> Enum.sort()
|> Enum.map(fn {_, v} -> v end)

ugly

for some backgrond info why this works see https://dockyard.com/blog/2019/04/01/erlang-term-ordering-evaluating-elixir-functions-part-2

1 Like

The way html forms encode data doesn‘t support lists of non-scalar data like things with multiple fields. One needs to index subfields to be able to reconstruct which fields belong together. That‘s why you get a map, not a list.

To not need to deal the limitations of html (as much) I‘d strongly suggest to not touch parameters before they‘ve been through ecto changeset validation. Ecto will handle the input being a map just fine if the schema/field is meant to be a list of things.

3 Likes