You are here

class ViewsSelection in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php \Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection
  2. 10 core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php \Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection

Plugin implementation of the 'selection' entity_reference.

Plugin annotation


@EntityReferenceSelection(
  id = "views",
  label = @Translation("Views: Filter by an entity reference view"),
  group = "views",
  weight = 0
)

Hierarchy

Expanded class hierarchy of ViewsSelection

File

core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php, line 30

Namespace

Drupal\views\Plugin\EntityReferenceSelection
View source
class ViewsSelection extends SelectionPluginBase implements ContainerFactoryPluginInterface {
  use DeprecatedServicePropertyTrait;
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  protected $deprecatedProperties = [
    'entityManager' => 'entity.manager',
  ];

  /**
   * The loaded View object.
   *
   * @var \Drupal\views\ViewExecutable
   */
  protected $view;

  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Constructs a new ViewsSelection object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Render\RendererInterface|null $renderer
   *   The renderer.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, RendererInterface $renderer = NULL) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
    $this->moduleHandler = $module_handler;
    $this->currentUser = $current_user;
    if (!$renderer) {
      @trigger_error('Calling ' . __METHOD__ . ' without the $renderer argument is deprecated in drupal:8.8.0 and is required in drupal:9.0.0. See https://www.drupal.org/node/2791359', E_USER_DEPRECATED);
      $renderer = \Drupal::service('renderer');
    }
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('module_handler'), $container
      ->get('current_user'), $container
      ->get('renderer'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'view' => [
        'view_name' => NULL,
        'display_name' => NULL,
        'arguments' => [],
      ],
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $view_settings = $this
      ->getConfiguration()['view'];
    $displays = Views::getApplicableViews('entity_reference_display');

    // Filter views that list the entity type we want, and group the separate
    // displays by view.
    $entity_type = $this->entityTypeManager
      ->getDefinition($this->configuration['target_type']);
    $view_storage = $this->entityTypeManager
      ->getStorage('view');
    $options = [];
    foreach ($displays as $data) {
      list($view_id, $display_id) = $data;
      $view = $view_storage
        ->load($view_id);
      if (in_array($view
        ->get('base_table'), [
        $entity_type
          ->getBaseTable(),
        $entity_type
          ->getDataTable(),
      ])) {
        $display = $view
          ->get('display');
        $options[$view_id . ':' . $display_id] = $view_id . ' - ' . $display[$display_id]['display_title'];
      }
    }

    // The value of the 'view_and_display' select below will need to be split
    // into 'view_name' and 'view_display' in the final submitted values, so
    // we massage the data at validate time on the wrapping element (not
    // ideal).
    $form['view']['#element_validate'] = [
      [
        get_called_class(),
        'settingsFormValidate',
      ],
    ];
    if ($options) {
      $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
      $form['view']['view_and_display'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('View used to select the entities'),
        '#required' => TRUE,
        '#options' => $options,
        '#default_value' => $default,
        '#description' => '<p>' . $this
          ->t('Choose the view and display that select the entities that can be referenced.<br />Only views with a display of type "Entity Reference" are eligible.') . '</p>',
      ];
      $default = !empty($view_settings['arguments']) ? implode(', ', $view_settings['arguments']) : '';
      $form['view']['arguments'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('View arguments'),
        '#default_value' => $default,
        '#required' => FALSE,
        '#description' => $this
          ->t('Provide a comma separated list of arguments to pass to the view.'),
      ];
    }
    else {
      if ($this->currentUser
        ->hasPermission('administer views') && $this->moduleHandler
        ->moduleExists('views_ui')) {
        $form['view']['no_view_help'] = [
          '#markup' => '<p>' . $this
            ->t('No eligible views were found. <a href=":create">Create a view</a> with an <em>Entity Reference</em> display, or add such a display to an <a href=":existing">existing view</a>.', [
            ':create' => Url::fromRoute('views_ui.add')
              ->toString(),
            ':existing' => Url::fromRoute('entity.view.collection')
              ->toString(),
          ]) . '</p>',
        ];
      }
      else {
        $form['view']['no_view_help']['#markup'] = '<p>' . $this
          ->t('No eligible views were found.') . '</p>';
      }
    }
    return $form;
  }

  /**
   * Initializes a view.
   *
   * @param string|null $match
   *   (Optional) Text to match the label against. Defaults to NULL.
   * @param string $match_operator
   *   (Optional) The operation the matching should be done with. Defaults
   *   to "CONTAINS".
   * @param int $limit
   *   Limit the query to a given number of items. Defaults to 0, which
   *   indicates no limiting.
   * @param array|null $ids
   *   Array of entity IDs. Defaults to NULL.
   *
   * @return bool
   *   Return TRUE if the view was initialized, FALSE otherwise.
   */
  protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
    $view_name = $this
      ->getConfiguration()['view']['view_name'];
    $display_name = $this
      ->getConfiguration()['view']['display_name'];

    // Check that the view is valid and the display still exists.
    $this->view = Views::getView($view_name);
    if (!$this->view || !$this->view
      ->access($display_name)) {
      \Drupal::messenger()
        ->addWarning($this
        ->t('The reference view %view_name cannot be found.', [
        '%view_name' => $view_name,
      ]));
      return FALSE;
    }
    $this->view
      ->setDisplay($display_name);

    // Pass options to the display handler to make them available later.
    $entity_reference_options = [
      'match' => $match,
      'match_operator' => $match_operator,
      'limit' => $limit,
      'ids' => $ids,
    ];
    $this->view->displayHandlers
      ->get($display_name)
      ->setOption('entity_reference_options', $entity_reference_options);
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $entities = [];
    if ($display_execution_results = $this
      ->getDisplayExecutionResults($match, $match_operator, $limit)) {
      $entities = $this
        ->stripAdminAndAnchorTagsFromResults($display_execution_results);
    }
    return $entities;
  }

  /**
   * Fetches the results of executing the display.
   *
   * @param string|null $match
   *   (Optional) Text to match the label against. Defaults to NULL.
   * @param string $match_operator
   *   (Optional) The operation the matching should be done with. Defaults
   *   to "CONTAINS".
   * @param int $limit
   *   Limit the query to a given number of items. Defaults to 0, which
   *   indicates no limiting.
   * @param array|null $ids
   *   Array of entity IDs. Defaults to NULL.
   *
   * @return array
   *   The results.
   */
  protected function getDisplayExecutionResults(string $match = NULL, string $match_operator = 'CONTAINS', int $limit = 0, array $ids = NULL) {
    $display_name = $this
      ->getConfiguration()['view']['display_name'];
    $arguments = $this
      ->getConfiguration()['view']['arguments'];
    $results = [];
    if ($this
      ->initializeView($match, $match_operator, $limit, $ids)) {
      $results = $this->view
        ->executeDisplay($display_name, $arguments);
    }
    return $results;
  }

  /**
   * Strips all admin and anchor tags from a result list.
   *
   * These results are usually displayed in an autocomplete field, which is
   * surrounded by anchor tags. Most tags are allowed inside anchor tags, except
   * for other anchor tags.
   *
   * @param array $results
   *   The result list.
   *
   * @return array
   *   The provided result list with anchor tags removed.
   */
  protected function stripAdminAndAnchorTagsFromResults(array $results) {
    $allowed_tags = Xss::getAdminTagList();
    if (($key = array_search('a', $allowed_tags)) !== FALSE) {
      unset($allowed_tags[$key]);
    }
    $stripped_results = [];
    foreach ($results as $id => $row) {
      $entity = $row['#row']->_entity;
      $stripped_results[$entity
        ->bundle()][$id] = ViewsRenderPipelineMarkup::create(Xss::filter($this->renderer
        ->renderPlain($row), $allowed_tags));
    }
    return $stripped_results;
  }

  /**
   * {@inheritdoc}
   */
  public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
    $this
      ->getReferenceableEntities($match, $match_operator);
    return $this->view->pager
      ->getTotalItems();
  }

  /**
   * {@inheritdoc}
   */
  public function validateReferenceableEntities(array $ids) {
    $entities = $this
      ->getDisplayExecutionResults(NULL, 'CONTAINS', 0, $ids);
    $result = [];
    if ($entities) {
      $result = array_keys($entities);
    }
    return $result;
  }

  /**
   * Element validate; Check View is valid.
   */
  public static function settingsFormValidate($element, FormStateInterface $form_state, $form) {

    // Split view name and display name from the 'view_and_display' value.
    if (!empty($element['view_and_display']['#value'])) {
      list($view, $display) = explode(':', $element['view_and_display']['#value']);
    }
    else {
      $form_state
        ->setError($element, t('The views entity selection mode requires a view.'));
      return;
    }

    // Explode the 'arguments' string into an actual array. Beware, explode()
    // turns an empty string into an array with one empty string. We'll need an
    // empty array instead.
    $arguments_string = trim($element['arguments']['#value']);
    if ($arguments_string === '') {
      $arguments = [];
    }
    else {

      // array_map() is called to trim whitespaces from the arguments.
      $arguments = array_map('trim', explode(',', $arguments_string));
    }
    $value = [
      'view_name' => $view,
      'display_name' => $display,
      'arguments' => $arguments,
    ];
    $form_state
      ->setValueForElement($element, $value);
  }

}

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
DeprecatedServicePropertyTrait::__get public function Allows to access deprecated/removed properties.
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.
SelectionPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
SelectionPluginBase::ensureBackwardCompatibilityConfiguration protected function Ensures a backward compatibility level configuration.
SelectionPluginBase::entityQueryAlter public function Allows the selection to alter the SelectQuery generated by EntityFieldQuery. Overrides SelectionInterface::entityQueryAlter 2
SelectionPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
SelectionPluginBase::resolveBackwardCompatibilityConfiguration protected function Moves the backward compatibility level configurations in the right place.
SelectionPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
SelectionPluginBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
SelectionPluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 1
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.
ViewsSelection::$currentUser protected property The current user.
ViewsSelection::$deprecatedProperties protected property
ViewsSelection::$entityTypeManager protected property The entity type manager service.
ViewsSelection::$moduleHandler protected property The module handler service.
ViewsSelection::$renderer protected property The renderer.
ViewsSelection::$view protected property The loaded View object.
ViewsSelection::buildConfigurationForm public function Form constructor. Overrides SelectionPluginBase::buildConfigurationForm
ViewsSelection::countReferenceableEntities public function Counts entities that are referenceable. Overrides SelectionInterface::countReferenceableEntities
ViewsSelection::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
ViewsSelection::defaultConfiguration public function Gets default configuration for this plugin. Overrides SelectionPluginBase::defaultConfiguration
ViewsSelection::getDisplayExecutionResults protected function Fetches the results of executing the display.
ViewsSelection::getReferenceableEntities public function Gets the list of referenceable entities. Overrides SelectionInterface::getReferenceableEntities
ViewsSelection::initializeView protected function Initializes a view.
ViewsSelection::settingsFormValidate public static function Element validate; Check View is valid.
ViewsSelection::stripAdminAndAnchorTagsFromResults protected function Strips all admin and anchor tags from a result list.
ViewsSelection::validateReferenceableEntities public function Validates which existing entities can be referenced. Overrides SelectionInterface::validateReferenceableEntities
ViewsSelection::__construct public function Constructs a new ViewsSelection object. Overrides SelectionPluginBase::__construct