You are here

class LinksWidget in Facets 8

The links widget.

Plugin annotation


@FacetsWidget(
  id = "links",
  label = @Translation("List of links"),
  description = @Translation("A simple widget that shows a list of links"),
)

Hierarchy

Expanded class hierarchy of LinksWidget

2 files declare their use of LinksWidget
FacetTest.php in tests/src/Kernel/Entity/FacetTest.php
LinksWidgetTest.php in tests/src/Unit/Plugin/widget/LinksWidgetTest.php

File

src/Plugin/facets/widget/LinksWidget.php, line 20

Namespace

Drupal\facets\Plugin\facets\widget
View source
class LinksWidget extends WidgetPluginBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'soft_limit' => 0,
      'soft_limit_settings' => [
        'show_less_label' => 'Show less',
        'show_more_label' => 'Show more',
      ],
      'show_reset_link' => FALSE,
      'hide_reset_when_no_selection' => FALSE,
      'reset_text' => $this
        ->t('Show all'),
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function build(FacetInterface $facet) {
    $build = parent::build($facet);
    $this
      ->appendWidgetLibrary($build);
    $soft_limit = (int) $this
      ->getConfiguration()['soft_limit'];
    if ($soft_limit !== 0) {
      $show_less_label = $this
        ->getConfiguration()['soft_limit_settings']['show_less_label'];
      $show_more_label = $this
        ->getConfiguration()['soft_limit_settings']['show_more_label'];
      $build['#attached']['library'][] = 'facets/soft-limit';
      $build['#attached']['drupalSettings']['facets']['softLimit'][$facet
        ->id()] = $soft_limit;
      $build['#attached']['drupalSettings']['facets']['softLimitSettings'][$facet
        ->id()]['showLessLabel'] = $show_less_label;
      $build['#attached']['drupalSettings']['facets']['softLimitSettings'][$facet
        ->id()]['showMoreLabel'] = $show_more_label;
    }
    if ($facet
      ->getUseHierarchy()) {
      $build['#attached']['library'][] = 'facets/drupal.facets.hierarchical';
    }
    $results = $facet
      ->getResults();
    if ($this
      ->getConfiguration()['show_reset_link'] && count($results) > 0 && (!$this
      ->getConfiguration()['hide_reset_when_no_selection'] || $facet
      ->getActiveItems())) {

      // Add reset link.
      $max_items = array_sum(array_map(function ($item) {
        return $item
          ->getCount();
      }, $results));
      $urlProcessorManager = \Drupal::service('plugin.manager.facets.url_processor');
      $url_processor = $urlProcessorManager
        ->createInstance($facet
        ->getFacetSourceConfig()
        ->getUrlProcessorName(), [
        'facet' => $facet,
      ]);
      $active_filters = $url_processor
        ->getActiveFilters();
      if (isset($active_filters[''])) {
        unset($active_filters['']);
      }
      unset($active_filters[$facet
        ->id()]);

      // Only if there are still active filters, use url generator.
      if ($active_filters) {
        $url = \Drupal::service('facets.utility.url_generator')
          ->getUrl($active_filters, FALSE);
      }
      else {
        $request = \Drupal::request();
        $url = Url::createFromRequest($request);
        $params = $request->query
          ->all();
        unset($params[$url_processor
          ->getFilterKey()]);
        if (\array_key_exists('page', $params)) {

          // Go back to the first page on reset.
          unset($params['page']);
        }
        $url
          ->setRouteParameter('facets_query', '');
        $url
          ->setOption('query', $params);
      }
      $result_item = new Result($facet, 'reset_all', $this
        ->getConfiguration()['reset_text'], $max_items);
      $result_item
        ->setActiveState(FALSE);
      $result_item
        ->setUrl($url);

      // Check if any other facet is in use.
      $none_active = TRUE;
      foreach ($results as $result) {
        if ($result
          ->isActive() || $result
          ->hasActiveChildren()) {
          $none_active = FALSE;
          break;
        }
      }

      // Add an is-active class when no other facet is in use.
      if ($none_active) {
        $result_item
          ->setActiveState(TRUE);
      }

      // Build item.
      $item = $this
        ->buildListItems($facet, $result_item);

      // Add a class for the reset link wrapper.
      $item['#wrapper_attributes']['class'][] = 'facets-reset';

      // Put reset facet link on first place.
      array_unshift($build['#items'], $item);
    }
    return $build;
  }

  /**
   * Appends widget library and relevant information for it to build array.
   *
   * @param array $build
   *   Reference to build array.
   */
  protected function appendWidgetLibrary(array &$build) {
    $build['#attached']['library'][] = 'facets/drupal.facets.link-widget';
    $build['#attributes']['class'][] = 'js-facets-links';
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state, FacetInterface $facet) {
    $form = parent::buildConfigurationForm($form, $form_state, $facet);
    $options = [
      50,
      40,
      30,
      20,
      15,
      10,
      5,
      3,
    ];
    $form['soft_limit'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Soft limit'),
      '#default_value' => $this
        ->getConfiguration()['soft_limit'],
      '#options' => [
        0 => $this
          ->t('No limit'),
      ] + array_combine($options, $options),
      '#description' => $this
        ->t('Limit the number of displayed facets via JavaScript.'),
    ];
    $form['soft_limit_settings'] = [
      '#type' => 'container',
      '#title' => $this
        ->t('Soft limit settings'),
      '#states' => [
        'invisible' => [
          ':input[name="widget_config[soft_limit]"]' => [
            'value' => 0,
          ],
        ],
      ],
    ];
    $form['soft_limit_settings']['show_less_label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Show less label'),
      '#description' => $this
        ->t('This text will be used for "Show less" link.'),
      '#default_value' => $this
        ->getConfiguration()['soft_limit_settings']['show_less_label'],
      '#states' => [
        'optional' => [
          ':input[name="widget_config[soft_limit]"]' => [
            'value' => 0,
          ],
        ],
      ],
    ];
    $form['soft_limit_settings']['show_more_label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Show more label'),
      '#description' => $this
        ->t('This text will be used for "Show more" link.'),
      '#default_value' => $this
        ->getConfiguration()['soft_limit_settings']['show_more_label'],
      '#states' => [
        'optional' => [
          ':input[name="widget_config[soft_limit]"]' => [
            'value' => 0,
          ],
        ],
      ],
    ];
    $form['show_reset_link'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show reset link'),
      '#default_value' => $this
        ->getConfiguration()['show_reset_link'],
    ];
    $form['reset_text'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Reset text'),
      '#default_value' => $this
        ->getConfiguration()['reset_text'],
      '#states' => [
        'visible' => [
          ':input[name="widget_config[show_reset_link]"]' => [
            'checked' => TRUE,
          ],
        ],
        'required' => [
          ':input[name="widget_config[show_reset_link]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['hide_reset_when_no_selection'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Hide reset link when no facet item is selected'),
      '#default_value' => $this
        ->getConfiguration()['hide_reset_when_no_selection'],
    ];
    return $form;
  }

}

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
LinksWidget::appendWidgetLibrary protected function Appends widget library and relevant information for it to build array. 1
LinksWidget::build public function Builds the facet widget for rendering. Overrides WidgetPluginBase::build
LinksWidget::buildConfigurationForm public function Provides a configuration form for this widget. Overrides WidgetPluginBase::buildConfigurationForm
LinksWidget::defaultConfiguration public function Gets default configuration for this plugin. Overrides WidgetPluginBase::defaultConfiguration
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.
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
WidgetPluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct