How do I hook up a changeset to a Phoenix 'select' list?

Does anyone have a link to a Phoenix example that shows how to hook up a ‘select’ list to a changeset? Imagine a dropdown list at the top of a table that contains different kinds of filters, eg. “all”, “active only”, etc etc

Apologies for being vague, I don’t know where to start. A working example would be fantastic!

Yeah - that’s vague!

So this may be one of many questions… Are you using the select to filter some data - a comprehensive example of dynamically building filters is here: What is the standard way to add filtering, sorting, pagination, sorting to Phoenix LiveViews? - #3 by anuvrat? Do you want inline editing in the table? Or is the select list “bound” to the changeset (i.e. used to update it)?

Not sure how to link my comment on another post direct but…

Is this what you’re looking for?

Add @options with your options in the formcomponent.ex and add :options to the socket.

  @options [
    {"Newest", "newest"}, 
    {"Oldest", "oldest"},
    {"Popular", "popular"}

  @impl true
  def update(%{example: example} = assigns, socket) do
    changeset = Example.change_example(example)
    |> assign(assigns)
    |> assign(:changeset, changeset)
    |> assign(:options, @options)

Your input type then just needs to be set to “select” and options are obviously the :options in the socket.

:example is whatever your database field is named

<.input field={f[:example]} type="select" options={@options} />
1 Like

That helps, thanks!

I put the list of options in the Changeset as well, which is where I ran into trouble. Couldn’t figure out what type the options should be in an Ecto schema(‘{:array, :tuple}’ wasn’t an option).

I put the list of options in the schema because I wanted to validate the ‘selected’ option, to ensure it’s a valid option from the list. But guess that’s not necessary, since the ‘select’ only presents a couple of predetermined/valid options to the user.

Super useful article, thank you. In this case my struggles were much more basic, but I’ll keep this one for reference :slight_smile: