select
Select field implements input field with drop down list giving possible values for the field.
Simplest select field can be defined like:
10:
name: site_permission
type: select
choices: NO_ACCESS:0,CAN_VIEW:1,CAN_EDIT:4
html:
include_blank: true
But it is more convenient to define choices for this field in locale translations. Choices are defined by keyword choices4_fieldname.
helpers:
label:
dc_policy_rule:
tabletitle: Access policy rules
choices4_site_permission: NO_ACCESS:0,CAN_VIEW:1,CAN_EDIT:4
Choices don't need to be always defined as description/value. Lots of times value of the field is also it's description.
Now to more interesting ways of providing choices. Choices can be provided by evaluating ruby method. Result of called method must be either one or two dimensional array of choices. Two scenarios are already covered.
10:
name: dc_site_id
type: select
eval: "dc_choices4('dc_site','name','id')"
or
eval: dc_choices4,dc_site,name,id
eval: dc_big_table 'key-name'
dc_choices4 takes parameters for model name, description and field providing return value (can be omitted). This scenario covers all belongs_to relations, where id value is related to record (document) in another collection (table).
Idea of dc_big_table is, to have options defined per installed application. Sometimes choices are subject of customer where the application is installed. By providing choices in dc_big_table, application can be customer tailored. Choices in dc_big table can also be localized.
Choices can be provided by calling any class method. Common place for defining this methods is in a model or controls.
fields:
10:
name: city
type: select
eval: Person.choices4_cities
and in person.rb
class Person def self.choices4_cities distinct(:name).inject([]) {|r,e| r << e} end end
In the example we extract only unique names of the cities provided in database.
Choices can also depend on the value of another field.
10:
name: country_code
type: select
choices: AT,DE,EN,SI
20:
name: city
type: select
eval: City.choices4_cities
depend: country_code
html:
include_blank: true
and in city.rb
class City def self.choices4_cities(country_code) where(country: country_code).distinct(:name).inject([]) {|r,e| r << e} end end
Although this example is much more suitable for text_autocomplete field, where additional values can be entered beside those suggested by application.
If you want to select multiple options with select field use multiple option. Be aware that in this case database field holding the value must be declared as Array.
10:
name: categories
type: select
eval: dc_choices4,dc_categories,name,id
multiple: true
and in document.rb
class Document field: categories, type: Array end
Selecting multiple options with default select control is not user friendly. Therefore when using multiple option, javascript select-multiple control is used to enter data.