Select options
Form fields Select, MultiSelect and RadioButton must have defined options for the user to choose from.
The basic way to define options is with an associated array, or iterator, where the key represents the future selected value and the value is what is displayed to the user.
Sometimes it may be necessary to influence the visual style of individual options. Let's take the administration of the sample application as an example. In the role administration, you use the MultiSelect field to select what permissions the role will have. Options are indented, groups of options are bolded ... Using a simple associated field would not be able to achieve this functionality in any easy and transparent way.
For this reason, each option is always represented by an instance of class Jet\Form_Field_Select_Option. Options can be defined directly as an array of instances of this class, or options can be defined as a simple array or iterator instance, and a form element instance of the Jet\Form_Field_Select_Option class will automatically create it. See example:
use Jet\Form_Field_Select;
use Jet\Logger;
use Jet\Tr;
$select_field = new Form_Field_Select('event_class', 'Event class:');
$select_field->setSelectOptions([
Logger::EVENT_CLASS_WARNING => Tr::_('Warning'),
Logger::EVENT_CLASS_DANGER => Tr::_('Danger'),
Logger::EVENT_CLASS_INFO => Tr::_('Info')
]);
$options = $select_field->getSelectOptions();
$options[Logger::EVENT_CLASS_WARNING]->setSelectOptionCssClass('warning');
$options[Logger::EVENT_CLASS_DANGER]->setSelectOptionCssClass('danger');
$options[Logger::EVENT_CLASS_INFO]->setSelectOptionCssClass('info');
$select_field->setSelectOptions( $options );
Beware! The form has built-in link to the translator. However, the form doesn't care about translating options because it doesn't know the logic of translating (what to translate, what not to translate, whether to add values, and so on).
Of course, an associated array is not the only way to define options. An option can be any object whose class implements the Jet\Form_Field_Select_Option_Interface. An example of such a class is Jet\Data_Tree_Node. That is, if you set as selection options a field containing objects implementing Jet\Form_Field_Select_Option_Interface interfaces, or an iterator providing such objects, then the form elements do not convert the values to instances of the Jet\Form_Field_Select_Option class, but keep the original instances as selection options.