Buttons.php in Select (or other) 4.x
File
src/Element/Buttons.php
View source
<?php
namespace Drupal\select_or_other\Element;
use Drupal\Core\Form\FormStateInterface;
class Buttons extends ElementBase {
public static function processSelectOrOther(&$element, FormStateInterface $form_state, &$complete_form) {
$element = parent::processSelectOrOther($element, $form_state, $complete_form);
static::setSelectType($element);
static::addStatesHandling($element);
static::addEmptyOption($element);
return $element;
}
protected static function setSelectType(array &$element) {
if ($element['#multiple']) {
$element['select']['#type'] = 'checkboxes';
}
else {
$element['select']['#type'] = 'radios';
static::ensureCorrectDefaultValue($element);
}
}
protected static function ensureCorrectDefaultValue(array &$element) {
if ($element['select']['#type'] === 'radios') {
if (!empty($element['select']['#default_value']) && is_array($element['select']['#default_value'])) {
$element['select']['#default_value'] = reset($element['select']['#default_value']);
}
}
}
protected static function addStatesHandling(array &$element) {
if (!$element['#multiple']) {
$element['other']['#states'] = static::prepareState('visible', $element['#name'] . '[select]', 'value', 'select_or_other');
}
else {
$element['other']['#states'] = static::prepareState('visible', $element['#name'] . '[select][select_or_other]', 'checked', TRUE);
}
}
protected static function addEmptyOption(array &$element) {
if (!isset($element['#no_empty_option']) || !$element['#no_empty_option']) {
if (!$element['#multiple'] && !$element['#required'] && !empty($element['#default_value'])) {
$element['select']['#options'] = [
'' => t('- None -'),
] + $element['select']['#options'];
}
else {
$element['select']['#value'] = [];
}
}
}
}
Classes
Name |
Description |
Buttons |
Provides a form element with buttons and other option. |