You are here

public static function Select2::preRenderSelect in Select 2 8

Prepares a select render element.

Overrides Select::preRenderSelect

2 calls to Select2::preRenderSelect()
Select2Test::testPlaceholderPropertyRendering in tests/src/Unit/Element/Select2Test.php
Checks #placeholder property.
Select2Test::testPreRenderSelect in tests/src/Unit/Element/Select2Test.php
@covers ::preRenderSelect

File

src/Element/Select2.php, line 244

Class

Select2
Provides an select2 form element.

Namespace

Drupal\select2\Element

Code

public static function preRenderSelect($element) {
  $element = parent::preRenderSelect($element);
  $required = isset($element['#states']['required']) ? TRUE : $element['#required'];
  $multiple = $element['#multiple'];
  if ($multiple) {
    $element['#attributes']['multiple'] = 'multiple';
    $element['#attributes']['name'] = $element['#name'] . '[]';
  }
  $current_language = \Drupal::languageManager()
    ->getCurrentLanguage();
  $current_theme = \Drupal::theme()
    ->getActiveTheme()
    ->getName();
  $select2_theme_exists = \Drupal::service('library.discovery')
    ->getLibraryByName($current_theme, 'select2.theme');

  // Placeholder should be taken from #placeholder property if it set.
  // Otherwise we can take it from '#empty_option' property.
  $placeholder_text = $required ? new TranslatableMarkup('- Select -') : new TranslatableMarkup('- None -');
  $placeholder = [
    'id' => '',
    'text' => $placeholder_text,
  ];
  if (!empty($element['#empty_value'])) {
    $placeholder['id'] = $element['#empty_value'];
  }
  if (!empty($element['#placeholder'])) {
    $placeholder['text'] = $element['#placeholder'];
  }
  elseif (!empty($element['#empty_option'])) {
    $placeholder['text'] = $element['#empty_option'];
  }

  // Defining the select2 configuration.
  $settings = [
    'multiple' => $multiple,
    'placeholder' => $placeholder,
    // @todo Enable allowClear for multiple fields. https://github.com/select2/select2/issues/3335.
    'allowClear' => !$multiple && !$required,
    'dir' => $current_language
      ->getDirection(),
    'language' => $current_language
      ->getId(),
    'tags' => (bool) $element['#autocreate'],
    'theme' => $select2_theme_exists ? $current_theme : 'default',
    'maximumSelectionLength' => $multiple ? $element['#cardinality'] : 0,
    'tokenSeparators' => $element['#autocreate'] ? [
      ',',
    ] : [],
    'selectOnClose' => $element['#autocomplete'],
    'width' => '100%',
  ];
  $element['#attributes']['class'][] = 'select2-widget';
  $element['#attributes']['data-select2-config'] = $settings;

  // Adding the select2 library.
  $element['#attached']['library'][] = 'select2/select2';
  $element['#attached']['library'][] = 'select2/select2.i18n.' . $current_language
    ->getId();
  if ($select2_theme_exists) {
    $element['#attached']['library'][] = $current_theme . '/select2.theme';
  }
  return $element;
}