3 namespace Drupal\Core\Field\Plugin\Field\FieldWidget;
5 use Drupal\Core\Field\FieldItemListInterface;
6 use Drupal\Core\Form\FormStateInterface;
9 * Plugin implementation of the 'options_buttons' widget.
12 * id = "options_buttons",
13 * label = @Translation("Check boxes/radio buttons"),
21 * multiple_values = TRUE
24 class OptionsButtonsWidget extends OptionsWidgetBase {
29 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
30 $element = parent::formElement($items, $delta, $element, $form, $form_state);
32 $options = $this->getOptions($items->getEntity());
33 $selected = $this->getSelectedOptions($items);
35 // If required and there is one single option, preselect it.
36 if ($this->required && count($options) == 1) {
38 $selected = [key($options)];
41 if ($this->multiple) {
43 '#type' => 'checkboxes',
44 '#default_value' => $selected,
45 '#options' => $options,
51 // Radio buttons need a scalar value. Take the first default value, or
52 // default to NULL so that the form element is properly recognized as
53 // not having a default value.
54 '#default_value' => $selected ? reset($selected) : NULL,
55 '#options' => $options,
65 protected function getEmptyLabel() {
66 if (!$this->required && !$this->multiple) {