SelectWidget.php

Contains \Drupal\options\Plugin\field\widget\SelectWidget.

Namespace

Drupal\options\Plugin\field\widget

File

drupal/core/modules/options/lib/Drupal/options/Plugin/field/widget/SelectWidget.php
View source
<?php

/**
 * @file
 * Contains \Drupal\options\Plugin\field\widget\SelectWidget.
 */
namespace Drupal\options\Plugin\field\widget;

use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;

/**
 * Plugin implementation of the 'options_select' widget.
 *
 * @Plugin(
 *   id = "options_select",
 *   module = "options",
 *   label = @Translation("Select list"),
 *   field_types = {
 *     "list_integer",
 *     "list_float",
 *     "list_text"
 *   },
 *   multiple_values = TRUE
 * )
 */
class SelectWidget extends OptionsWidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
    $element = parent::formElement($items, $delta, $element, $langcode, $form, $form_state);
    $element += array(
      '#type' => 'select',
      '#options' => $this
        ->getOptions(),
      '#default_value' => $this
        ->getSelectedOptions($items),
      // Do not display a 'multiple' select box if there is only one option.
      '#multiple' => $this->multiple && count($this->options) > 1,
    );
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  protected static function sanitizeLabel(&$label) {

    // Select form inputs allow unencoded HTML entities, but no HTML tags.
    $label = strip_tags($label);
  }

  /**
   * {@inheritdoc}
   */
  protected function supportsGroups() {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEmptyOption() {
    if ($this->multiple) {

      // Multiple select: add a 'none' option for non-required fields.
      if (!$this->required) {
        return static::OPTIONS_EMPTY_NONE;
      }
    }
    else {

      // Single select: add a 'none' option for non-required fields,
      // and a 'select a value' option for required fields that do not come
      // with a value selected.
      if (!$this->required) {
        return static::OPTIONS_EMPTY_NONE;
      }
      if (!$this->has_value) {
        return static::OPTIONS_EMPTY_SELECT;
      }
    }
  }

}

Classes

Namesort descending Description
SelectWidget Plugin implementation of the 'options_select' widget.