Select Options
:single_select and :multi_select form fields (rendered with TomSelect) get their options in one of four ways: a static collection, the model's enum, a helper_method, or a remote options_url. A field can also refill another field when its value changes.
Quick exampleβ
cm_section "Mode Of Transport" do
form_field :status, input_type: :single_select, collection: [["Vehicle", "vehicle"], ["Bike", "bike"]]
form_field :transport_type_id, input_type: :single_select, helper_method: :transport_type_options
end
app/helpers/cm_admin/custom_helper.rb
def transport_type_options(_record, _field_name)
Constant.where(type: "transport_type").map { |item| [item.full_name, item.id] }
end
Optionsβ
The first match wins:
| Source | Option | Format |
|---|---|---|
| Helper method | helper_method: :name | Method in CmAdmin::CustomHelper called with (record, field_name); returns [[label, value], ...]. |
| Static list | collection: [...] | [[label, value], ...] or [value, ...]. |
| Enum | none | Used automatically when the field is an enum: [[key.titleize, key], ...]. |
| Remote URL | options_url: "/path" | Fetched as the user types. See Load options from a URL. |
Recipesβ
Load options from a URLβ
Use options_url for large lists. TomSelect requests the URL with the typed text in the search parameter and expects an array of id / title hashes.
form_field :optional_language_id, input_type: :single_select, label: "Optional Language",
options_url: "/admin/students/optional_languages"
A custom action that returns a Hash or an Array is rendered as JSON, so it can serve the options:
cm_index do
custom_action name: "optional_languages", route_type: :collection, verb: "get",
path: "optional_languages", display_type: :route do
::Constant.search_constant_by_name(params[:search], "optional_language")
.map { |language| { id: language.id, title: language.name.titleize } }
end
end
Refill another field when a value changesβ
Add target: { action_name: ... } to the field that drives the change. When its value changes, cm-admin calls that action with the new value (?transport_type_id=3) and applies the fields in the response.
form_field :transport_type_id, input_type: :single_select, helper_method: :transport_type_options,
target: { action_name: :fetch_routes }
form_field :route_id, input_type: :single_select
custom_action name: "fetch_routes", route_type: :collection, verb: "get", path: "fetch_routes", display_type: :route do
routes = ::Route.where(transport_type_id: params[:transport_type_id]).map { |route| [route.name, route.id] }
{ fields: [{ target_type: :select, target_value: { table: "student", field_name: "route_id", field_value: routes } }] }
end
target_type | Effect on the field #<table>_<field_name> |
|---|---|
select | Replaces its options with field_value ([[label, value], ...]). |
input | Sets its value to field_value. |
toggle_visibility | Shows or hides the field. |
Initialise a select from your own JavaScriptβ
Use window.cmSelect.