OptionsButtonsWidget.php

Same filename in other branches
  1. 9 core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/OptionsButtonsWidget.php
  2. 8.9.x core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/OptionsButtonsWidget.php
  3. 10 core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/OptionsButtonsWidget.php

Namespace

Drupal\Core\Field\Plugin\Field\FieldWidget

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\Attribute\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Plugin implementation of the 'options_buttons' widget.
 */
class OptionsButtonsWidget extends OptionsWidgetBase {
    
    /**
     * {@inheritdoc}
     */
    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 required and there is one single option, preselect it.
        if ($this->required && count($options) == 1) {
            $selected = [
                array_key_first($options),
            ];
        }
        if ($this->multiple) {
            $element += [
                '#type' => 'checkboxes',
                '#default_value' => $selected,
                '#options' => $options,
            ];
        }
        else {
            $element += [
                '#type' => 'radios',
                // Radio buttons need a scalar value. Take the first default value, or
                // default to NULL so that the form element is properly recognized as
                // not having a default value.
'#default_value' => $selected ? reset($selected) : NULL,
                '#options' => $options,
            ];
        }
        return $element;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function getEmptyLabel() {
        if (!$this->required && !$this->multiple) {
            return $this->t('N/A');
        }
    }

}

Classes

Title Deprecated Summary
OptionsButtonsWidget Plugin implementation of the 'options_buttons' widget.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.