public static function ElementBase::valueCallback in Select (or other) 8
Same name and namespace in other branches
- 8.3 src/Element/ElementBase.php \Drupal\select_or_other\Element\ElementBase::valueCallback()
- 4.x src/Element/ElementBase.php \Drupal\select_or_other\Element\ElementBase::valueCallback()
Determines how user input is mapped to an element's #value property.
Parameters
array $element: An associative array containing the properties of the element.
mixed $input: The incoming input to populate the form element. If this is FALSE, the element's default value should be returned.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Return value
mixed The value to assign to the element.
Overrides FormElement::valueCallback
1 call to ElementBase::valueCallback()
- ElementsTest::testValueCallback in tests/
src/ Unit/ ElementsTest.php - Tests the value callback.
File
- src/
Element/ ElementBase.php, line 158
Class
- ElementBase
- Base class for select or other form elements.
Namespace
Drupal\select_or_other\ElementCode
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
if (self::elementIsDisabled($element) || self::noElementAccess($element)) {
unset($element['#value']);
return NULL;
}
$values = [];
if ($input !== FALSE && !empty($input['select'])) {
if ($element['#multiple']) {
$values = [
'select' => (array) $input['select'],
'other' => !empty($input['other']) ? (array) $input['other'] : [],
];
if (in_array('select_or_other', $values['select'])) {
$values['select'] = array_diff($values['select'], [
'select_or_other',
]);
}
else {
$values['other'] = [];
}
if (isset($element['#merged_values']) && $element['#merged_values']) {
if (!empty($values['other'])) {
if (is_array($values['select']) && array_key_exists('select_or_other', $values['select'])) {
$select = array_pop($values['select']) !== NULL ? array_pop($values['select']) : [];
$values = array_values(array_merge($select, $values['other']));
}
else {
$values = array_values(array_merge($values['select'], $values['other']));
}
// Add the other option to the available options to prevent
// validation errors.
$element['#options'][$input['other']] = $input['other'];
}
else {
$select = array_filter($values['select']);
$values = array_values($select);
}
}
}
else {
if ($input['select'] === 'select_or_other') {
$values = [
$input['other'],
];
// Add the other option to the available options to prevent
// validation errors.
$element['#options'][$input['other']] = $input['other'];
}
else {
$values = [
$input['select'],
];
}
}
}
return $values;
}