I have an app in which I list parents and children. When I add a child, I need to get a list of parents to be shows as a drop list. Is there something like a collection_select
in Rails available in Phoenix? I would like to display the name of the user and use user_id as a param.
I also want to scope the list of parents by site_id.
You can use the select/4 function from Phoenix.HTML.Form
.
In your controller you can fetch fetch the parents with a query:
query = from(p in Parent, select: {p.id, p.name})
parents = Repo.all(query)
The reason we need this query is to format the values in the expected format:
Values are expected to be an Enumerable containing two-item tuples (like maps and keyword lists) or any Enumerable where the element will be used both as key and value for the generated select.
You can then use select/4
in your template:
<%= select f, :parent_id, @parents ,class: "form-control" %>
You can also transform the records using Enum.map/2 if you already have the parents:
parents = Repo.all(Parent) |> Enum.map(&{&1.id, &1.name})
all_parents = Repo.all from p in Parent, select: {p.name, p.id}
<%= select f, :parent_id, @all_parents %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With