Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir Phoenix helper for associated model list

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.

like image 672
Pratik Khadloya Avatar asked Dec 05 '15 08:12

Pratik Khadloya


2 Answers

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})
like image 117
Gazler Avatar answered Sep 30 '22 07:09

Gazler


controller

all_parents = Repo.all from p in Parent, select: {p.name, p.id}

eex

<%= select f, :parent_id, @all_parents %>
like image 27
ryanwinchester Avatar answered Sep 30 '22 09:09

ryanwinchester