You are here

public static function Select2::preRenderAutocomplete in Select 2 8

Attach autocomplete behavior to the render element.

2 calls to Select2::preRenderAutocomplete()
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 303

Class

Select2
Provides an select2 form element.

Namespace

Drupal\select2\Element

Code

public static function preRenderAutocomplete($element) {
  if (!$element['#autocomplete']) {
    return $element;
  }
  $value_callable = isset($element['#autocomplete_route_callback']) ? $element['#autocomplete_route_callback'] : NULL;
  if (!$value_callable || !is_callable($value_callable)) {
    $value_callable = '\\Drupal\\select2\\Element\\Select2::setAutocompleteRouteParameters';
  }
  $element = call_user_func_array($value_callable, [
    &$element,
  ]);

  // Reduce options to the preselected ones and bring them in the correct
  // order.
  $options = OptGroup::flattenOptions($element['#options']);
  $values = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
  $values = is_array($values) ? $values : [
    $values,
  ];
  $element['#options'] = [];
  foreach ($values as $value) {
    if (isset($options[$value])) {
      $element['#options'][$value] = $options[$value];
    }
  }

  /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
  $access_manager = \Drupal::service('access_manager');
  $access = $access_manager
    ->checkNamedRoute($element['#autocomplete_route_name'], $element['#autocomplete_route_parameters'], \Drupal::currentUser(), TRUE);
  if ($access && $access
    ->isAllowed()) {
    $url = Url::fromRoute($element['#autocomplete_route_name'], $element['#autocomplete_route_parameters'])
      ->toString(TRUE);

    // Provide a data attribute for the JavaScript behavior to bind to.
    $element['#attributes']['data-select2-config'] += [
      'minimumInputLength' => 1,
      'ajax' => [
        'delay' => 250,
        'url' => $url
          ->getGeneratedUrl(),
      ],
    ];
  }
  return $element;
}