How to add all items in an array into a select field?

I’ve got a seemingly simple question. Let’s say I have an array:

array = ["Item-1", "Item 2", "Another", "Last"]

render(conn, "new.html", id: id, array: array, changeset: changeset)

And I’ve got a select field in a form file:

<%= select f, :options, [???], prompt: "Select an answer" %>

And I wanted to end up with a select field that works like this:

Screenshot 2022-01-27 at 18.35.10

The value being the same as the value on display. (i.e the value of “Item-1” will also be “Item-1”)

How would I do this in the form? What would I put into the [???] opt in the select field?

You would just put your @array in there.

Following select/4 you are using the last option for options:

atom, string or integer - which will be used as both label and value for the generated select

So it would look something similar to this:

<%= select f, :options, @array, prompt: "Select an answer" %>
2 Likes

Lol! I think I’ve lost my mind. Cheers that works haha.

Let’s say we actually have a List:wink:

btw, you can also pass a list of two-element tuples to select/4, a Keyword list like [{"Item-1", 1}, {"Item-2", 2}] in case you need to show a text value but want to use its id as the option’s value. A list of lists [["Item-1", 1], ["Item-2", 2]] should work too if I’m not mistaken.

2 Likes