aa791651fc823a024922b7a92770524874e64049
[yaffs-website] / web / core / modules / views / src / Plugin / EntityReferenceSelection / ViewsSelection.php
1 <?php
2
3 namespace Drupal\views\Plugin\EntityReferenceSelection;
4
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;
9 use Drupal\Core\Url;
10 use Drupal\views\Views;
11
12 /**
13  * Plugin implementation of the 'selection' entity_reference.
14  *
15  * @EntityReferenceSelection(
16  *   id = "views",
17  *   label = @Translation("Views: Filter by an entity reference view"),
18  *   group = "views",
19  *   weight = 0
20  * )
21  */
22 class ViewsSelection extends SelectionPluginBase implements ContainerFactoryPluginInterface {
23
24   use SelectionTrait;
25
26   /**
27    * The loaded View object.
28    *
29    * @var \Drupal\views\ViewExecutable
30    */
31   protected $view;
32
33   /**
34    * {@inheritdoc}
35    */
36   public function defaultConfiguration() {
37     return [
38       'view' => [
39         'view_name' => NULL,
40         'display_name' => NULL,
41         'arguments' => [],
42       ],
43     ] + parent::defaultConfiguration();
44   }
45
46   /**
47    * {@inheritdoc}
48    */
49   public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
50     $form = parent::buildConfigurationForm($form, $form_state);
51
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
55     // displays by view.
56     $entity_type = $this->entityManager->getDefinition($this->configuration['target_type']);
57     $view_storage = $this->entityManager->getStorage('view');
58
59     $options = [];
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'];
66       }
67     }
68
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
72     // ideal).
73     $form['view']['#element_validate'] = [[get_called_class(), 'settingsFormValidate']];
74
75     if ($options) {
76       $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
77       $form['view']['view_and_display'] = [
78         '#type' => 'select',
79         '#title' => $this->t('View used to select the entities'),
80         '#required' => TRUE,
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>',
84       ];
85
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,
91         '#required' => FALSE,
92         '#description' => $this->t('Provide a comma separated list of arguments to pass to the view.'),
93       ];
94     }
95     else {
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(),
101           ]) . '</p>',
102         ];
103       }
104       else {
105         $form['view']['no_view_help']['#markup'] = '<p>' . $this->t('No eligible views were found.') . '</p>';
106       }
107     }
108     return $form;
109   }
110
111   /**
112    * Initializes a view.
113    *
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
118    *   to "CONTAINS".
119    * @param int $limit
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.
124    *
125    * @return bool
126    *   Return TRUE if the view was initialized, FALSE otherwise.
127    */
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'];
131
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]));
136       return FALSE;
137     }
138     $this->view->setDisplay($display_name);
139
140     // Pass options to the display handler to make them available later.
141     $entity_reference_options = [
142       'match' => $match,
143       'match_operator' => $match_operator,
144       'limit' => $limit,
145       'ids' => $ids,
146     ];
147     $this->view->displayHandlers->get($display_name)->setOption('entity_reference_options', $entity_reference_options);
148     return TRUE;
149   }
150
151   /**
152    * {@inheritdoc}
153    */
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'];
157     $result = [];
158     if ($this->initializeView($match, $match_operator, $limit)) {
159       // Get the results.
160       $result = $this->view->executeDisplay($display_name, $arguments);
161     }
162
163     $return = [];
164     if ($result) {
165       foreach ($this->view->result as $row) {
166         $entity = $row->_entity;
167         $return[$entity->bundle()][$entity->id()] = $entity->label();
168       }
169     }
170     return $return;
171   }
172
173   /**
174    * {@inheritdoc}
175    */
176   public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
177     $this->getReferenceableEntities($match, $match_operator);
178     return $this->view->pager->getTotalItems();
179   }
180
181   /**
182    * {@inheritdoc}
183    */
184   public function validateReferenceableEntities(array $ids) {
185     $display_name = $this->getConfiguration()['view']['display_name'];
186     $arguments = $this->getConfiguration()['view']['arguments'];
187     $result = [];
188     if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
189       // Get the results.
190       $entities = $this->view->executeDisplay($display_name, $arguments);
191       $result = array_keys($entities);
192     }
193     return $result;
194   }
195
196   /**
197    * Element validate; Check View is valid.
198    */
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']);
203     }
204     else {
205       $form_state->setError($element, t('The views entity selection mode requires a view.'));
206       return;
207     }
208
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 === '') {
214       $arguments = [];
215     }
216     else {
217       // array_map() is called to trim whitespaces from the arguments.
218       $arguments = array_map('trim', explode(',', $arguments_string));
219     }
220
221     $value = ['view_name' => $view, 'display_name' => $display, 'arguments' => $arguments];
222     $form_state->setValueForElement($element, $value);
223   }
224
225 }