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

Hi,

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>
    </div>
  <% 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>

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

  <div class="form-group">
    <%= submit "Submit", class: "btn btn-primary" %>
  </div>
<% 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

    timestamps()
  end

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

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

Thanks
Sudheer

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: {a.name, a.id}

Or so?

1 Like

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