The select filter renders a select box for the implemented options/1 and prompt/0 callbacks. The prompt/0 callback defines the key for the nil value added as first option.
See the following example for an implementation of an event status filter.
defmodule MyAppWeb.Filters.EventStatusSelect do
use Backpex.Filters.Select
@impl Backpex.Filter
def label, do: "Event status"
@impl Backpex.Filters.Select
def prompt, do: "Select an option..."
@impl Backpex.Filters.Select
def options(_assigns), do: [
{"Open", :open},
{"Close", :close},
]
@impl Backpex.Filter
def query(query, attribute, value) do
where(query, [x], field(x, ^attribute) == ^value)
end
enduse Backpex.Filters.Select
When you use Backpex.Filters.Select, the Backpex.Filters.Select module will set @behavior Backpex.Filters.Select.
In addition it will add a render and render_form function in order to display the corresponding filter.
Summary
Functions
Validates that the selected value exists in the options list.
Finds the label for a given option value.
Converts empty string to nil, returns other values as-is.
Callbacks
Functions
Validates that the selected value exists in the options list.
Returns the changeset unchanged if the value is valid, or adds an error if not found in options. Empty string is allowed as it represents the "no selection" state.
Finds the label for a given option value.
Returns nil if the value is not found.
Examples
iex> options = [{"Open", :open}, {"Closed", :closed}]
iex> Backpex.Filters.Select.option_value_to_label(options, "open")
"Open"
iex> options = [{"Open", :open}]
iex> Backpex.Filters.Select.option_value_to_label(options, :open)
"Open"
iex> options = [{"Open", :open}]
iex> Backpex.Filters.Select.option_value_to_label(options, "unknown")
nil
iex> options = [{"Active", "active"}, {"Inactive", "inactive"}]
iex> Backpex.Filters.Select.option_value_to_label(options, "active")
"Active"
iex> options = [{"Active", "active"}]
iex> Backpex.Filters.Select.option_value_to_label(options, :active)
"Active"
iex> Backpex.Filters.Select.option_value_to_label([], "value")
nil
Attributes
value(:any) (required)options(:list) (required)
Attributes
form(:any) (required)field(:atom) (required)value(:any) (required)options(:list) (required)prompt(:string) (required)errors(:list) - Defaults to[].
Converts empty string to nil, returns other values as-is.
Examples
iex> Backpex.Filters.Select.selected("")
nil
iex> Backpex.Filters.Select.selected("open")
"open"
iex> Backpex.Filters.Select.selected(:open)
:open
iex> Backpex.Filters.Select.selected(1)
1