You are here

public function Select2Widget::build in Select 2 8

Builds the facet widget for rendering.

Parameters

\Drupal\facets\FacetInterface $facet: The facet we need to build.

Return value

array A renderable array.

Overrides WidgetPluginBase::build

File

modules/select2_facets/src/Plugin/facets/widget/Select2Widget.php, line 76

Class

Select2Widget
The select2 widget.

Namespace

Drupal\select2_facets\Plugin\facets\widget

Code

public function build(FacetInterface $facet) {
  $this->facet = $facet;
  $items = [];
  $active_items = [];
  foreach ($facet
    ->getResults() as $result) {
    if (empty($result
      ->getUrl())) {
      continue;
    }
    $count = $result
      ->getCount();
    $this->showNumbers = $this
      ->getConfiguration()['show_numbers'] && $count !== NULL;
    $items[$result
      ->getUrl()
      ->toString()] = $this->showNumbers ? sprintf('%s (%d)', $result
      ->getDisplayValue(), $result
      ->getCount()) : $result
      ->getDisplayValue();
    if ($result
      ->isActive()) {
      $active_items[] = $result
        ->getUrl()
        ->toString();
    }
  }
  $element = [
    '#type' => 'select2',
    '#options' => $items,
    '#required' => FALSE,
    '#value' => $active_items,
    '#multiple' => !$facet
      ->getShowOnlyOneResult(),
    '#autocomplete' => $this
      ->getConfiguration()['autocomplete'],
    '#name' => $facet
      ->getName(),
    '#title' => $facet
      ->get('show_title') ? $facet
      ->getName() : '',
    '#attributes' => [
      'data-drupal-facet-id' => $facet
        ->id(),
      'data-drupal-selector' => 'facet-' . $facet
        ->id(),
      'class' => [
        'js-facets-select2',
        'js-facets-widget',
      ],
    ],
    '#attached' => [
      'library' => [
        'select2_facets/drupal.select2_facets.select2-widget',
      ],
    ],
    '#cache' => [
      'contexts' => [
        'url.path',
        'url.query_args',
      ],
    ],
    '#select2' => [
      'width' => $this
        ->getConfiguration()['width'],
    ],
  ];
  if ($element['#autocomplete']) {
    $element['#autocomplete_route_callback'] = [
      $this,
      'processFacetAutocomplete',
    ];
  }
  return $element;
}