Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / lib / Drupal / Core / Field / Plugin / Field / FieldWidget / OptionsButtonsWidget.php
1 <?php
2
3 namespace Drupal\Core\Field\Plugin\Field\FieldWidget;
4
5 use Drupal\Core\Field\FieldItemListInterface;
6 use Drupal\Core\Form\FormStateInterface;
7
8 /**
9  * Plugin implementation of the 'options_buttons' widget.
10  *
11  * @FieldWidget(
12  *   id = "options_buttons",
13  *   label = @Translation("Check boxes/radio buttons"),
14  *   field_types = {
15  *     "boolean",
16  *     "entity_reference",
17  *     "list_integer",
18  *     "list_float",
19  *     "list_string",
20  *   },
21  *   multiple_values = TRUE
22  * )
23  */
24 class OptionsButtonsWidget extends OptionsWidgetBase {
25
26   /**
27    * {@inheritdoc}
28    */
29   public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
30     $element = parent::formElement($items, $delta, $element, $form, $form_state);
31
32     $options = $this->getOptions($items->getEntity());
33     $selected = $this->getSelectedOptions($items);
34
35     // If required and there is one single option, preselect it.
36     if ($this->required && count($options) == 1) {
37       reset($options);
38       $selected = [key($options)];
39     }
40
41     if ($this->multiple) {
42       $element += [
43         '#type' => 'checkboxes',
44         '#default_value' => $selected,
45         '#options' => $options,
46       ];
47     }
48     else {
49       $element += [
50         '#type' => 'radios',
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,
56       ];
57     }
58
59     return $element;
60   }
61
62   /**
63    * {@inheritdoc}
64    */
65   protected function getEmptyLabel() {
66     if (!$this->required && !$this->multiple) {
67       return t('N/A');
68     }
69   }
70
71 }