Version 1
[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\Database\Query\SelectInterface;
6 use Drupal\Core\Entity\EntityManagerInterface;
7 use Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface;
8 use Drupal\Core\Extension\ModuleHandlerInterface;
9 use Drupal\Core\Form\FormStateInterface;
10 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
11 use Drupal\Core\Plugin\PluginBase;
12 use Drupal\Core\Session\AccountInterface;
13 use Drupal\Core\Url;
14 use Drupal\views\Views;
15 use Symfony\Component\DependencyInjection\ContainerInterface;
16
17 /**
18  * Plugin implementation of the 'selection' entity_reference.
19  *
20  * @EntityReferenceSelection(
21  *   id = "views",
22  *   label = @Translation("Views: Filter by an entity reference view"),
23  *   group = "views",
24  *   weight = 0
25  * )
26  */
27 class ViewsSelection extends PluginBase implements SelectionInterface, ContainerFactoryPluginInterface {
28
29   /**
30    * The entity manager.
31    *
32    * @var \Drupal\Core\Entity\EntityManagerInterface
33    */
34   protected $entityManager;
35
36   /**
37    * The module handler service.
38    *
39    * @var \Drupal\Core\Extension\ModuleHandlerInterface
40    */
41   protected $moduleHandler;
42
43   /**
44    * The current user.
45    *
46    * @var \Drupal\Core\Session\AccountInterface
47    */
48   protected $currentUser;
49
50   /**
51    * Constructs a new SelectionBase object.
52    *
53    * @param array $configuration
54    *   A configuration array containing information about the plugin instance.
55    * @param string $plugin_id
56    *   The plugin_id for the plugin instance.
57    * @param mixed $plugin_definition
58    *   The plugin implementation definition.
59    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
60    *   The entity manager service.
61    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
62    *   The module handler service.
63    * @param \Drupal\Core\Session\AccountInterface $current_user
64    *   The current user.
65    */
66   public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user) {
67     parent::__construct($configuration, $plugin_id, $plugin_definition);
68
69     $this->entityManager = $entity_manager;
70     $this->moduleHandler = $module_handler;
71     $this->currentUser = $current_user;
72   }
73
74   /**
75    * {@inheritdoc}
76    */
77   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
78     return new static(
79       $configuration,
80       $plugin_id,
81       $plugin_definition,
82       $container->get('entity.manager'),
83       $container->get('module_handler'),
84       $container->get('current_user')
85     );
86   }
87
88   /**
89    * The loaded View object.
90    *
91    * @var \Drupal\views\ViewExecutable;
92    */
93   protected $view;
94
95   /**
96    * {@inheritdoc}
97    */
98   public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
99     $selection_handler_settings = $this->configuration['handler_settings'];
100     $view_settings = !empty($selection_handler_settings['view']) ? $selection_handler_settings['view'] : [];
101     $displays = Views::getApplicableViews('entity_reference_display');
102     // Filter views that list the entity type we want, and group the separate
103     // displays by view.
104     $entity_type = $this->entityManager->getDefinition($this->configuration['target_type']);
105     $view_storage = $this->entityManager->getStorage('view');
106
107     $options = [];
108     foreach ($displays as $data) {
109       list($view_id, $display_id) = $data;
110       $view = $view_storage->load($view_id);
111       if (in_array($view->get('base_table'), [$entity_type->getBaseTable(), $entity_type->getDataTable()])) {
112         $display = $view->get('display');
113         $options[$view_id . ':' . $display_id] = $view_id . ' - ' . $display[$display_id]['display_title'];
114       }
115     }
116
117     // The value of the 'view_and_display' select below will need to be split
118     // into 'view_name' and 'view_display' in the final submitted values, so
119     // we massage the data at validate time on the wrapping element (not
120     // ideal).
121     $form['view']['#element_validate'] = [[get_called_class(), 'settingsFormValidate']];
122
123     if ($options) {
124       $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
125       $form['view']['view_and_display'] = [
126         '#type' => 'select',
127         '#title' => $this->t('View used to select the entities'),
128         '#required' => TRUE,
129         '#options' => $options,
130         '#default_value' => $default,
131         '#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>',
132       ];
133
134       $default = !empty($view_settings['arguments']) ? implode(', ', $view_settings['arguments']) : '';
135       $form['view']['arguments'] = [
136         '#type' => 'textfield',
137         '#title' => $this->t('View arguments'),
138         '#default_value' => $default,
139         '#required' => FALSE,
140         '#description' => $this->t('Provide a comma separated list of arguments to pass to the view.'),
141       ];
142     }
143     else {
144       if ($this->currentUser->hasPermission('administer views') && $this->moduleHandler->moduleExists('views_ui')) {
145         $form['view']['no_view_help'] = [
146           '#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>.', [
147             ':create' => Url::fromRoute('views_ui.add')->toString(),
148             ':existing' => Url::fromRoute('entity.view.collection')->toString(),
149           ]) . '</p>',
150         ];
151       }
152       else {
153         $form['view']['no_view_help']['#markup'] = '<p>' . $this->t('No eligible views were found.') . '</p>';
154       }
155     }
156     return $form;
157   }
158
159   /**
160    * {@inheritdoc}
161    */
162   public function validateConfigurationForm(array &$form, FormStateInterface $form_state) { }
163
164   /**
165    * {@inheritdoc}
166    */
167   public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { }
168
169   /**
170    * Initializes a view.
171    *
172    * @param string|null $match
173    *   (Optional) Text to match the label against. Defaults to NULL.
174    * @param string $match_operator
175    *   (Optional) The operation the matching should be done with. Defaults
176    *   to "CONTAINS".
177    * @param int $limit
178    *   Limit the query to a given number of items. Defaults to 0, which
179    *   indicates no limiting.
180    * @param array|null $ids
181    *   Array of entity IDs. Defaults to NULL.
182    *
183    * @return bool
184    *   Return TRUE if the view was initialized, FALSE otherwise.
185    */
186   protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
187     $handler_settings = $this->configuration['handler_settings'];
188     $view_name = $handler_settings['view']['view_name'];
189     $display_name = $handler_settings['view']['display_name'];
190
191     // Check that the view is valid and the display still exists.
192     $this->view = Views::getView($view_name);
193     if (!$this->view || !$this->view->access($display_name)) {
194       drupal_set_message(t('The reference view %view_name cannot be found.', ['%view_name' => $view_name]), 'warning');
195       return FALSE;
196     }
197     $this->view->setDisplay($display_name);
198
199     // Pass options to the display handler to make them available later.
200     $entity_reference_options = [
201       'match' => $match,
202       'match_operator' => $match_operator,
203       'limit' => $limit,
204       'ids' => $ids,
205     ];
206     $this->view->displayHandlers->get($display_name)->setOption('entity_reference_options', $entity_reference_options);
207     return TRUE;
208   }
209
210   /**
211    * {@inheritdoc}
212    */
213   public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
214     $handler_settings = $this->configuration['handler_settings'];
215     $display_name = $handler_settings['view']['display_name'];
216     $arguments = $handler_settings['view']['arguments'];
217     $result = [];
218     if ($this->initializeView($match, $match_operator, $limit)) {
219       // Get the results.
220       $result = $this->view->executeDisplay($display_name, $arguments);
221     }
222
223     $return = [];
224     if ($result) {
225       foreach ($this->view->result as $row) {
226         $entity = $row->_entity;
227         $return[$entity->bundle()][$entity->id()] = $entity->label();
228       }
229     }
230     return $return;
231   }
232
233   /**
234    * {@inheritdoc}
235    */
236   public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
237     $this->getReferenceableEntities($match, $match_operator);
238     return $this->view->pager->getTotalItems();
239   }
240
241   /**
242    * {@inheritdoc}
243    */
244   public function validateReferenceableEntities(array $ids) {
245     $handler_settings = $this->configuration['handler_settings'];
246     $display_name = $handler_settings['view']['display_name'];
247     $arguments = $handler_settings['view']['arguments'];
248     $result = [];
249     if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
250       // Get the results.
251       $entities = $this->view->executeDisplay($display_name, $arguments);
252       $result = array_keys($entities);
253     }
254     return $result;
255   }
256
257   /**
258    * Element validate; Check View is valid.
259    */
260   public static function settingsFormValidate($element, FormStateInterface $form_state, $form) {
261     // Split view name and display name from the 'view_and_display' value.
262     if (!empty($element['view_and_display']['#value'])) {
263       list($view, $display) = explode(':', $element['view_and_display']['#value']);
264     }
265     else {
266       $form_state->setError($element, t('The views entity selection mode requires a view.'));
267       return;
268     }
269
270     // Explode the 'arguments' string into an actual array. Beware, explode()
271     // turns an empty string into an array with one empty string. We'll need an
272     // empty array instead.
273     $arguments_string = trim($element['arguments']['#value']);
274     if ($arguments_string === '') {
275       $arguments = [];
276     }
277     else {
278       // array_map() is called to trim whitespaces from the arguments.
279       $arguments = array_map('trim', explode(',', $arguments_string));
280     }
281
282     $value = ['view_name' => $view, 'display_name' => $display, 'arguments' => $arguments];
283     $form_state->setValueForElement($element, $value);
284   }
285
286   /**
287    * {@inheritdoc}
288    */
289   public function entityQueryAlter(SelectInterface $query) { }
290
291 }