Phoenix.Html.Form Question. How to use "array names" for example name[] for input name

Hello,

I got a little question here.
In Html we sometimes we append ‘[]’ to the input names in form, as an example below.

<input name="input1[]" type="text" />
<input name="input1[]" type="text" />
<input name="input1[]" type="text" /> 
...

My questions are -
First - In General, how do phoenix handle these kind of inputs? Do phoenix converts to them tuple type on the fly as they are in ordered. Let’s try it out.

Second - How do use Phoenix.Html.Form to generate the tags in the form. I have some think that it should work but it didn’t.
This is what I have tried -

<%= form_for @conn, @action, [as: "purchase"], fn f -> %>
<%= text_input f, :roll %>
<%end %>

The above code resulting in generating below tag -

<input name="purchase[roll[]]" type="text" /> 

Which isn’t what we want?

Dev.

3 Likes

With this code

<input name="input1[]" type="text" value="1" />
<input name="input1[]" type="text" value="2" />
<input name="input1[]" type="text" value="3" />

We are getting this as elixir list and in the order of first come in the form first we can extract from the list. I really like this.

[“1”,“2”,“3”]

But still couldn’t figure out how to use the Phoenix.Html.Form to generate html for this.

Dev.

Pass the name option to the functions, for example: text_input f, :input1, name: "input1[]". Not sure if that’s exactly the option but it something along the lines above.

10 Likes

Thank you very much Jose Valim.


Dev.

For anyone that arrives here via google and is looking to see how to add an array field within a model you can use

<%= text_input f, :input1, name: "game[player_names][]" %>

So that will add a player_name array within the game_params in your controller.

9 Likes