formex_ecto v0.2.3 Formex.Ecto.CustomField.SelectAssoc View Source
This module generates a :select
field with options downloaded from Repo.
Example of use for Article with one Category:
schema "articles" do
belongs_to :category, App.Category
end
form
|> add(:category_id, Formex.Ecto.CustomField.SelectAssoc, label: "Category")
Formex will find out that :category_id
refers to App.Category schema and download all rows
from Repo ordered by name.
If you are using :without_choices
option (from Formex.Field.create_field/3
), you don’t
need to implement :choice_label_provider
, this module will do it for you.
Options
choice_label
- controls the content of<option>
. May be the name of a field or a function. Example of use:form |> add(:article_id, SelectAssoc, label: "Article", choice_label: :title)
form |> add(:user_id, SelectAssoc, label: "User", choice_label: fn user -> user.first_name<>" "<>user.last_name end)
query
- an additional query that filters the choices list. Example of use:form |> add(:user_id, SelectAssoc, query: fn query -> from e in query, where: e.fired == false end)
group_by
- wraps<option>
’s in<optgroup>
’s. May be:field_name
,:assoc_name
or[:assoc_name, :field_name]
Example of use:
schema "users" do field :first_name, :string field :last_name, :string belongs_to :department, App.Department end
schema "departments" do field :name, :string field :description, :string end
Group by last name of user:
form |> add(:user_id, SelectAssoc, group_by: :last_name)
Group by department, by
:name
(default) field:form |> add(:user_id, SelectAssoc, group_by: :department)
Group by department, but by another field
form |> add(:user_id, SelectAssoc, group_by: [:department, :description])
search_field
- schema field to be used in query insearch/3
. If it’s anil
, then the final value depends on thechoice_label
value:- if
:choice_label
is nil,:search_field
becomes:name
- if
:choice_label
is an atom,:search_field
gets this atom - if
:choice_label
is a function,:search_field
is still nil
- if
search_query
- if thesearch_field
functionality is not enough for you, use this to apply your own query. It’s necessary if you have more than one field to search, e.g. first name and last name.
Link to this section Summary
Functions
Can be used in controller, along with :without_choices
option from
Formex.Field.create_field/3
Link to this section Functions
search(form :: Formex.Form.t, name :: atom, search :: String.t) :: List.t
Can be used in controller, along with :without_choices
option from
Formex.Field.create_field/3
.
It gets rows from repo that matches given search
argument and returns them as
{label, id}
list.
Example of use for Ajax-Bootstrap-Select:
def search_categories(conn, %{"q" => search}) do
result = create_form(App.ArticleType, %Article{})
|> Formex.Ecto.CustomField.SelectAssoc.search(:category_id, search)
|> Enum.map(fn {label, id} -> %{
"value" => id,
"text" => label
} end)
json(conn, result)
end