Form with nested multiple objects

Hello folks.

I’ve got a funny template issue. Basically I want a form that returns multiple objects (the number of objects returned is undefined).

So one solution would be to retrieve something like that in serialized parameter: %{"products" => %{"101" => %{...}, "102" => %{...}, ...}} (where the numbers are the ids of products).

Right now I use a form tag with option as: :products. And inside the loop of each product, something like this for a field:

= number_input f, "#{}][stock", value: product.stock

As you can see, the string "#{}][stock" looks weird but it works as expected because the name attributes are generated like this : product[101][stock]

Do you see a better way for this trick?

Lol, old fashioned escaping and merging in a string parameter, I love it. ^.^

Works fine, although I’d probably make a custom number_input for that purpose or so. I’m not sure if that format is ‘set’ through versions, though I’d think it would be…

I do a lot of adding [...] and so forth to fields as well.

For note though, you might look at the inputs_for function in Phoenix.HTML.Form, for this case it should be suited I’d think without seeing the rest of your code.



yes you’re right, I’ve tried to include the nested field in something like:

= inputs_for f, "#{}", fn fp

And it works for the nested fields using just the attribute names as strings and without the brackets…


1 Like