You are here

class Select2Widget in Select 2 8

Same name in this branch
  1. 8 src/Plugin/Field/FieldWidget/Select2Widget.php \Drupal\select2\Plugin\Field\FieldWidget\Select2Widget
  2. 8 modules/select2_facets/src/Plugin/facets/widget/Select2Widget.php \Drupal\select2_facets\Plugin\facets\widget\Select2Widget

The select2 widget.

Plugin annotation


@FacetsWidget(
  id = "select2",
  label = @Translation("Select2"),
  description = @Translation("A configurable widget that shows a select2."),
)

Hierarchy

Expanded class hierarchy of Select2Widget

File

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

Namespace

Drupal\select2_facets\Plugin\facets\widget
View source
class Select2Widget extends WidgetPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The current request.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * The key-value store for entity_autocomplete.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  protected $keyValueStore;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Request $request, KeyValueStoreInterface $key_value_store) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->request = $request;
    $this->keyValueStore = $key_value_store;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('request_stack')
      ->getCurrentRequest(), $container
      ->get('keyvalue')
      ->get('entity_autocomplete'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'autocomplete' => FALSE,
      'match_operator' => 'CONTAINS',
      'width' => '100%',
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state, FacetInterface $facet) {
    $form = parent::buildConfigurationForm($form, $form_state, $facet);
    $form['width'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Field width'),
      '#default_value' => $this
        ->getConfiguration()['width'],
      '#description' => $this
        ->t("Define a width for the select2 field. It can be either 'element', 'computedstyle', 'style', 'resolve' or any possible CSS unit. E.g. 500px, 50%, 200em. See the <a href='https://select2.org/appearance#container-width'>select2 documentation</a> for further explanations."),
      '#required' => TRUE,
      '#size' => '12',
      '#pattern' => "([0-9]*\\.[0-9]+|[0-9]+)(cm|mm|in|px|pt|pc|em|ex|ch|rem|vm|vh|vmin|vmax|%)|element|computedstyle|style|resolve|auto|initial|inherit",
    ];
    $form['autocomplete'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Autocomplete'),
      '#default_value' => $this
        ->getConfiguration()['autocomplete'],
      '#description' => $this
        ->t('Options will be lazy loaded. This is recommended for lists with a lot of values.'),
    ];
    $form['match_operator'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Autocomplete matching'),
      '#default_value' => $this
        ->getConfiguration()['match_operator'],
      '#options' => $this
        ->getMatchOperatorOptions(),
      '#description' => $this
        ->t('Select the method used to collect autocomplete suggestions. Note that <em>Contains</em> can cause performance issues on sites with thousands of entities.'),
      '#states' => [
        'visible' => [
          ':input[name$="widget_config[autocomplete]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    return $form;
  }

  /**
   * Returns the options for the match operator.
   *
   * @return array
   *   List of options.
   */
  protected function getMatchOperatorOptions() {
    return [
      'STARTS_WITH' => $this
        ->t('Starts with'),
      'CONTAINS' => $this
        ->t('Contains'),
    ];
  }

  /**
   * Set the autocomplete route properties.
   *
   * @param array $element
   *   The render element.
   *
   * @return array
   *   The render element with autocomplete settings.
   */
  public function processFacetAutocomplete(array &$element) {
    $selection_settings = [
      'path' => $this->request
        ->getUri(),
      'match_operator' => $this
        ->getConfiguration()['match_operator'],
      'show_numbers' => $this
        ->getConfiguration()['show_numbers'],
    ];

    // Store the selection settings in the key/value store and pass a hashed key
    // in the route parameters.
    $data = serialize($selection_settings) . $this->facet
      ->getFacetSourceId() . $this->facet
      ->id();
    $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());
    if (!$this->keyValueStore
      ->has($selection_settings_key)) {
      $this->keyValueStore
        ->set($selection_settings_key, $selection_settings);
    }
    $element['#autocomplete_route_name'] = 'select2_facets.facet_autocomplete';
    $element['#autocomplete_route_parameters'] = [
      'facetsource_id' => $this->facet
        ->getFacetSourceId(),
      'facet_id' => $this->facet
        ->id(),
      'selection_settings_key' => $selection_settings_key,
    ];
    return $element;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
Select2Widget::$keyValueStore protected property The key-value store for entity_autocomplete.
Select2Widget::$request protected property The current request.
Select2Widget::build public function Builds the facet widget for rendering. Overrides WidgetPluginBase::build
Select2Widget::buildConfigurationForm public function Provides a configuration form for this widget. Overrides WidgetPluginBase::buildConfigurationForm
Select2Widget::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
Select2Widget::defaultConfiguration public function Gets default configuration for this plugin. Overrides WidgetPluginBase::defaultConfiguration
Select2Widget::getMatchOperatorOptions protected function Returns the options for the match operator.
Select2Widget::processFacetAutocomplete public function Set the autocomplete route properties.
Select2Widget::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides WidgetPluginBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
WidgetPluginBase::$facet protected property The facet the widget is being built for.
WidgetPluginBase::$showNumbers protected property Show the amount of results next to the result.
WidgetPluginBase::buildListItems protected function Builds a renderable array of result items. 1
WidgetPluginBase::buildResultItem protected function Builds a facet result item.
WidgetPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
WidgetPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
WidgetPluginBase::getFacetItemListThemeHook protected function Provides a full array of possible theme functions to try for a given hook.
WidgetPluginBase::getQueryType public function Picks the preferred query type for this widget. Overrides WidgetPluginInterface::getQueryType 3
WidgetPluginBase::isPropertyRequired public function Checks is a specific property is required for this widget. Overrides WidgetPluginInterface::isPropertyRequired 2
WidgetPluginBase::prepareLink protected function Returns the text or link for an item.
WidgetPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
WidgetPluginBase::supportsFacet public function Checks if the facet is supported by this processor. Overrides WidgetPluginInterface::supportsFacet 1