annotate core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php @ 19:fa3358dc1485 tip

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