formex v0.3.2 Formex.CustomField.SelectAssoc

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(Formex.CustomField.SelectAssoc, :category_id, label: "Category")

Formex will find out that :category_id refers to App.Category schema and download all rows from Repo ordered by name.

Options

  • choice_label - controls the content of <option>. May be the name of a field or a function. Example of use:

    form
    |> add(SelectAssoc, :article_id, label: "Article", choice_label: :title)
    form
    |> add(SelectAssoc, :user_id, 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(SelectAssoc, :user_id, 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(SelectAssoc, :user_id, group_by: :last_name)

    Group by department, by :name (default) field:

    form
    |> add(SelectAssoc, :user_id, group_by: :department)

    Group by department, but by another field

    form
    |> add(SelectAssoc, :user_id, group_by: [:department, :description])

Summary

Functions

create_field(form, name, opts)

Function that generates Formex.Field.t/0, similary to Formex.Field.create_field/4

Callback implementation for Formex.CustomField.create_field/3.