OptionsButtonsWidget.php in Drupal 9
File
core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/OptionsButtonsWidget.php
View source
<?php
namespace Drupal\Core\Field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
class OptionsButtonsWidget extends OptionsWidgetBase {
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$options = $this
->getOptions($items
->getEntity());
$selected = $this
->getSelectedOptions($items);
if ($this->required && count($options) == 1) {
reset($options);
$selected = [
key($options),
];
}
if ($this->multiple) {
$element += [
'#type' => 'checkboxes',
'#default_value' => $selected,
'#options' => $options,
];
}
else {
$element += [
'#type' => 'radios',
'#default_value' => $selected ? reset($selected) : NULL,
'#options' => $options,
];
}
return $element;
}
protected function getEmptyLabel() {
if (!$this->required && !$this->multiple) {
return t('N/A');
}
}
}