Skip to main content

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:

SourceOptionFormat
Helper methodhelper_method: :nameMethod in CmAdmin::CustomHelper called with (record, field_name); returns [[label, value], ...].
Static listcollection: [...][[label, value], ...] or [value, ...].
EnumnoneUsed automatically when the field is an enum: [[key.titleize, key], ...].
Remote URLoptions_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_typeEffect on the field #<table>_<field_name>
selectReplaces its options with field_value ([[label, value], ...]).
inputSets its value to field_value.
toggle_visibilityShows or hides the field.

Initialise a select from your own JavaScript​

Use window.cmSelect.