3 namespace Drupal\views\Plugin\EntityReferenceSelection;
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;
14 use Drupal\views\Views;
15 use Symfony\Component\DependencyInjection\ContainerInterface;
18 * Plugin implementation of the 'selection' entity_reference.
20 * @EntityReferenceSelection(
22 * label = @Translation("Views: Filter by an entity reference view"),
27 class ViewsSelection extends PluginBase implements SelectionInterface, ContainerFactoryPluginInterface {
32 * @var \Drupal\Core\Entity\EntityManagerInterface
34 protected $entityManager;
37 * The module handler service.
39 * @var \Drupal\Core\Extension\ModuleHandlerInterface
41 protected $moduleHandler;
46 * @var \Drupal\Core\Session\AccountInterface
48 protected $currentUser;
51 * Constructs a new SelectionBase object.
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
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);
69 $this->entityManager = $entity_manager;
70 $this->moduleHandler = $module_handler;
71 $this->currentUser = $current_user;
77 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
82 $container->get('entity.manager'),
83 $container->get('module_handler'),
84 $container->get('current_user')
89 * The loaded View object.
91 * @var \Drupal\views\ViewExecutable;
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
104 $entity_type = $this->entityManager->getDefinition($this->configuration['target_type']);
105 $view_storage = $this->entityManager->getStorage('view');
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'];
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
121 $form['view']['#element_validate'] = [[get_called_class(), 'settingsFormValidate']];
124 $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
125 $form['view']['view_and_display'] = [
127 '#title' => $this->t('View used to select the entities'),
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>',
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.'),
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(),
153 $form['view']['no_view_help']['#markup'] = '<p>' . $this->t('No eligible views were found.') . '</p>';
162 public function validateConfigurationForm(array &$form, FormStateInterface $form_state) { }
167 public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { }
170 * Initializes a view.
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
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.
184 * Return TRUE if the view was initialized, FALSE otherwise.
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'];
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');
197 $this->view->setDisplay($display_name);
199 // Pass options to the display handler to make them available later.
200 $entity_reference_options = [
202 'match_operator' => $match_operator,
206 $this->view->displayHandlers->get($display_name)->setOption('entity_reference_options', $entity_reference_options);
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'];
218 if ($this->initializeView($match, $match_operator, $limit)) {
220 $result = $this->view->executeDisplay($display_name, $arguments);
225 foreach ($this->view->result as $row) {
226 $entity = $row->_entity;
227 $return[$entity->bundle()][$entity->id()] = $entity->label();
236 public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
237 $this->getReferenceableEntities($match, $match_operator);
238 return $this->view->pager->getTotalItems();
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'];
249 if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
251 $entities = $this->view->executeDisplay($display_name, $arguments);
252 $result = array_keys($entities);
258 * Element validate; Check View is valid.
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']);
266 $form_state->setError($element, t('The views entity selection mode requires a view.'));
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 === '') {
278 // array_map() is called to trim whitespaces from the arguments.
279 $arguments = array_map('trim', explode(',', $arguments_string));
282 $value = ['view_name' => $view, 'display_name' => $display, 'arguments' => $arguments];
283 $form_state->setValueForElement($element, $value);
289 public function entityQueryAlter(SelectInterface $query) { }