How to populate select options of a form from a database table?


I have a “form.html.eex” as follows for model “titles” to create new titles.

<%= form_for @changeset, @action, fn f -> %>
  <%= if @changeset.action do %>
    <div class="alert alert-danger">
    <p>Oops, something went wrong! Please check the errors below.</p>
  <% end %>

  <div class="form-group">
    <%= label f, :author_id, class: "control-label" %>
    <%= select f, :author_id, ["AuthorName1": "1",
   "AuthorName2": "2"], class: "form-control" %>
   <%= error_tag f, :author_id %>

  <div class="form-group">
    <%= label f, :name, class: "control-label" %>
    <%= text_input f, :name, class: "form-control" %>
    <%= error_tag f, :name %>

  <div class="form-group">
    <%= submit "Submit", class: "btn btn-primary" %>
<% end %>

The form works correctly. I have currently hard coded the options for the select field in this form. The Author model looks like as follows

defmodule HelloPhoenix.Author do
  use HelloPhoenix.Web, :model

  schema "authors" do
    field :name, :string
    has_many :titles, HelloPhoenix.Title


  @doc """
  Builds a changeset based on the `struct` and `params`.
  def changeset(struct, params \\ %{}) do
    |> cast(params, [:name])
    |> validate_required([:name])

I would like to populate the options of the select field from this Authors table. How do I go about doing that?


You should be able to just craft an ecto query that returns the table information in the format you directly want, in which case just pass the result to the template from the controller and give it to the select instead of your hard-coded list. :slight_smile:

Something like this for the query:

from a in Authors,
  select: {,}

Or so?

1 Like

@OvermindDL1: Thanks for the suggestion. I will try it over the weekend and let you know.