3 namespace Drupal\views\Plugin\EntityReferenceSelection;
5 use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginBase;
6 use Drupal\Core\Entity\EntityReferenceSelection\SelectionTrait;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
10 use Drupal\views\Views;
13 * Plugin implementation of the 'selection' entity_reference.
15 * @EntityReferenceSelection(
17 * label = @Translation("Views: Filter by an entity reference view"),
22 class ViewsSelection extends SelectionPluginBase implements ContainerFactoryPluginInterface {
27 * The loaded View object.
29 * @var \Drupal\views\ViewExecutable
36 public function defaultConfiguration() {
40 'display_name' => NULL,
43 ] + parent::defaultConfiguration();
49 public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
50 $form = parent::buildConfigurationForm($form, $form_state);
52 $view_settings = $this->getConfiguration()['view'];
53 $displays = Views::getApplicableViews('entity_reference_display');
54 // Filter views that list the entity type we want, and group the separate
56 $entity_type = $this->entityManager->getDefinition($this->configuration['target_type']);
57 $view_storage = $this->entityManager->getStorage('view');
60 foreach ($displays as $data) {
61 list($view_id, $display_id) = $data;
62 $view = $view_storage->load($view_id);
63 if (in_array($view->get('base_table'), [$entity_type->getBaseTable(), $entity_type->getDataTable()])) {
64 $display = $view->get('display');
65 $options[$view_id . ':' . $display_id] = $view_id . ' - ' . $display[$display_id]['display_title'];
69 // The value of the 'view_and_display' select below will need to be split
70 // into 'view_name' and 'view_display' in the final submitted values, so
71 // we massage the data at validate time on the wrapping element (not
73 $form['view']['#element_validate'] = [[get_called_class(), 'settingsFormValidate']];
76 $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
77 $form['view']['view_and_display'] = [
79 '#title' => $this->t('View used to select the entities'),
81 '#options' => $options,
82 '#default_value' => $default,
83 '#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>',
86 $default = !empty($view_settings['arguments']) ? implode(', ', $view_settings['arguments']) : '';
87 $form['view']['arguments'] = [
88 '#type' => 'textfield',
89 '#title' => $this->t('View arguments'),
90 '#default_value' => $default,
92 '#description' => $this->t('Provide a comma separated list of arguments to pass to the view.'),
96 if ($this->currentUser->hasPermission('administer views') && $this->moduleHandler->moduleExists('views_ui')) {
97 $form['view']['no_view_help'] = [
98 '#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>.', [
99 ':create' => Url::fromRoute('views_ui.add')->toString(),
100 ':existing' => Url::fromRoute('entity.view.collection')->toString(),
105 $form['view']['no_view_help']['#markup'] = '<p>' . $this->t('No eligible views were found.') . '</p>';
112 * Initializes a view.
114 * @param string|null $match
115 * (Optional) Text to match the label against. Defaults to NULL.
116 * @param string $match_operator
117 * (Optional) The operation the matching should be done with. Defaults
120 * Limit the query to a given number of items. Defaults to 0, which
121 * indicates no limiting.
122 * @param array|null $ids
123 * Array of entity IDs. Defaults to NULL.
126 * Return TRUE if the view was initialized, FALSE otherwise.
128 protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
129 $view_name = $this->getConfiguration()['view']['view_name'];
130 $display_name = $this->getConfiguration()['view']['display_name'];
132 // Check that the view is valid and the display still exists.
133 $this->view = Views::getView($view_name);
134 if (!$this->view || !$this->view->access($display_name)) {
135 \Drupal::messenger()->addWarning(t('The reference view %view_name cannot be found.', ['%view_name' => $view_name]));
138 $this->view->setDisplay($display_name);
140 // Pass options to the display handler to make them available later.
141 $entity_reference_options = [
143 'match_operator' => $match_operator,
147 $this->view->displayHandlers->get($display_name)->setOption('entity_reference_options', $entity_reference_options);
154 public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
155 $display_name = $this->getConfiguration()['view']['display_name'];
156 $arguments = $this->getConfiguration()['view']['arguments'];
158 if ($this->initializeView($match, $match_operator, $limit)) {
160 $result = $this->view->executeDisplay($display_name, $arguments);
165 foreach ($this->view->result as $row) {
166 $entity = $row->_entity;
167 $return[$entity->bundle()][$entity->id()] = $entity->label();
176 public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
177 $this->getReferenceableEntities($match, $match_operator);
178 return $this->view->pager->getTotalItems();
184 public function validateReferenceableEntities(array $ids) {
185 $display_name = $this->getConfiguration()['view']['display_name'];
186 $arguments = $this->getConfiguration()['view']['arguments'];
188 if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
190 $entities = $this->view->executeDisplay($display_name, $arguments);
191 $result = array_keys($entities);
197 * Element validate; Check View is valid.
199 public static function settingsFormValidate($element, FormStateInterface $form_state, $form) {
200 // Split view name and display name from the 'view_and_display' value.
201 if (!empty($element['view_and_display']['#value'])) {
202 list($view, $display) = explode(':', $element['view_and_display']['#value']);
205 $form_state->setError($element, t('The views entity selection mode requires a view.'));
209 // Explode the 'arguments' string into an actual array. Beware, explode()
210 // turns an empty string into an array with one empty string. We'll need an
211 // empty array instead.
212 $arguments_string = trim($element['arguments']['#value']);
213 if ($arguments_string === '') {
217 // array_map() is called to trim whitespaces from the arguments.
218 $arguments = array_map('trim', explode(',', $arguments_string));
221 $value = ['view_name' => $view, 'display_name' => $display, 'arguments' => $arguments];
222 $form_state->setValueForElement($element, $value);