DefaultSelection.php 17.1 KB
Newer Older
1 2 3 4 5 6
<?php

namespace Drupal\Core\Entity\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\Core\Database\Query\AlterableInterface;
7 8
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Entity\EntityFieldManagerInterface;
9
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginBase;
10
use Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface;
11 12 13
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
14
use Drupal\Core\Entity\FieldableEntityInterface;
15
use Drupal\Core\Extension\ModuleHandlerInterface;
16
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
17 18
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
19
use Drupal\Core\Session\AccountInterface;
20
use Drupal\user\EntityOwnerInterface;
21
use Symfony\Component\DependencyInjection\ContainerInterface;
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

/**
 * Default plugin implementation of the Entity Reference Selection plugin.
 *
 * Also serves as a base class for specific types of Entity Reference
 * Selection plugins.
 *
 * @see \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManager
 * @see \Drupal\Core\Entity\Annotation\EntityReferenceSelection
 * @see \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface
 * @see \Drupal\Core\Entity\Plugin\Derivative\DefaultSelectionDeriver
 * @see plugin_api
 *
 * @EntityReferenceSelection(
 *   id = "default",
 *   label = @Translation("Default"),
 *   group = "default",
 *   weight = 0,
 *   deriver = "Drupal\Core\Entity\Plugin\Derivative\DefaultSelectionDeriver"
 * )
 */
43
class DefaultSelection extends SelectionPluginBase implements ContainerFactoryPluginInterface, SelectionWithAutocreateInterface {
44
  use DeprecatedServicePropertyTrait;
45

46 47 48 49 50 51 52 53
  /**
   * {@inheritdoc}
   */
  protected $deprecatedProperties = ['entityManager' => 'entity.manager'];

  /**
   * The entity type manager service.
   *
54
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
   */
  protected $entityTypeManager;

  /**
   * The entity field manager service.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * Entity type bundle info service.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  public $entityTypeBundleInfo;

  /**
   * The entity repository.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * Constructs a new DefaultSelection object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle info service.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, EntityFieldManagerInterface $entity_field_manager = NULL, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, EntityRepositoryInterface $entity_repository = NULL) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->entityTypeManager = $entity_type_manager;
    $this->moduleHandler = $module_handler;
    $this->currentUser = $current_user;

    if (!$entity_field_manager) {
      @trigger_error('Calling DefaultSelection::__construct() with the $entity_field_manager argument is supported in drupal:8.7.0 and will be required before drupal:9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
      $entity_field_manager = \Drupal::service('entity_field.manager');
    }
    $this->entityFieldManager = $entity_field_manager;

    if (!$entity_type_bundle_info) {
      @trigger_error('Calling DefaultSelection::__construct() with the $entity_type_bundle_info argument is supported in drupal:8.7.0 and will be required before drupal:9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
      $entity_type_bundle_info = \Drupal::service('entity_type.bundle.info');
    }
    $this->entityTypeBundleInfo = $entity_type_bundle_info;

    if (!$entity_repository) {
      @trigger_error('Calling DefaultSelection::__construct() with the $entity_repository argument is supported in drupal:8.7.0 and will be required before drupal:9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
      $entity_repository = \Drupal::service('entity.repository');
    }
    $this->entityRepository = $entity_repository;
139 140 141 142 143
  }

  /**
   * {@inheritdoc}
   */
144 145 146 147 148 149 150 151 152 153 154 155
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
      $container->get('module_handler'),
      $container->get('current_user'),
      $container->get('entity_field.manager'),
      $container->get('entity_type.bundle.info'),
      $container->get('entity.repository')
    );
156
  }
157 158 159 160

  /**
   * {@inheritdoc}
   */
161 162
  public function defaultConfiguration() {
    return [
163 164 165 166
      // For the 'target_bundles' setting, a NULL value is equivalent to "allow
      // entities from any bundle to be referenced" and an empty array value is
      // equivalent to "no entities from any bundle can be referenced".
      'target_bundles' => NULL,
167
      'sort' => [
168
        'field' => '_none',
169
        'direction' => 'ASC',
170
      ],
171
      'auto_create' => FALSE,
172
      'auto_create_bundle' => NULL,
173 174 175 176 177 178 179 180 181 182 183
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $configuration = $this->getConfiguration();
    $entity_type_id = $configuration['target_type'];
184 185
    $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
    $bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
186 187

    if ($entity_type->hasKey('bundle')) {
188
      $bundle_options = [];
189 190 191
      foreach ($bundles as $bundle_name => $bundle_info) {
        $bundle_options[$bundle_name] = $bundle_info['label'];
      }
192
      natsort($bundle_options);
193

194
      $form['target_bundles'] = [
195
        '#type' => 'checkboxes',
196
        '#title' => $entity_type->getBundleLabel(),
197
        '#options' => $bundle_options,
198
        '#default_value' => (array) $configuration['target_bundles'],
199 200 201
        '#required' => TRUE,
        '#size' => 6,
        '#multiple' => TRUE,
202
        '#element_validate' => [[get_class($this), 'elementValidateFilter']],
203 204
        '#ajax' => TRUE,
        '#limit_validation_errors' => [],
205
      ];
206 207 208 209 210 211 212 213 214 215

      $form['target_bundles_update'] = [
        '#type' => 'submit',
        '#value' => $this->t('Update form'),
        '#limit_validation_errors' => [],
        '#attributes' => [
          'class' => ['js-hide'],
        ],
        '#submit' => [[EntityReferenceItem::class, 'settingsAjaxSubmit']],
      ];
216 217
    }
    else {
218
      $form['target_bundles'] = [
219
        '#type' => 'value',
220 221
        '#value' => [],
      ];
222 223
    }

224
    if ($entity_type->entityClassImplements(FieldableEntityInterface::class)) {
225
      $fields = [];
226
      foreach (array_keys($bundles) as $bundle) {
227
        $bundle_fields = array_filter($this->entityFieldManager->getFieldDefinitions($entity_type_id, $bundle), function ($field_definition) {
228 229 230 231 232 233 234 235 236 237
          return !$field_definition->isComputed();
        });
        foreach ($bundle_fields as $field_name => $field_definition) {
          /* @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
          $columns = $field_definition->getFieldStorageDefinition()->getColumns();
          // If there is more than one column, display them all, otherwise just
          // display the field label.
          // @todo: Use property labels instead of the column name.
          if (count($columns) > 1) {
            foreach ($columns as $column_name => $column_info) {
238
              $fields[$field_name . '.' . $column_name] = $this->t('@label (@column)', ['@label' => $field_definition->getLabel(), '@column' => $column_name]);
239 240 241
            }
          }
          else {
242
            $fields[$field_name] = $this->t('@label', ['@label' => $field_definition->getLabel()]);
243 244 245 246
          }
        }
      }

247
      $form['sort']['field'] = [
248 249
        '#type' => 'select',
        '#title' => $this->t('Sort by'),
250
        '#options' => [
251
          '_none' => $this->t('- None -'),
252
        ] + $fields,
253
        '#ajax' => TRUE,
254
        '#limit_validation_errors' => [],
255
        '#default_value' => $configuration['sort']['field'],
256
      ];
257

258
      $form['sort']['settings'] = [
259
        '#type' => 'container',
260
        '#attributes' => ['class' => ['entity_reference-settings']],
261
        '#process' => [[EntityReferenceItem::class, 'formProcessMergeParent']],
262
      ];
263

264
      if ($configuration['sort']['field'] != '_none') {
265
        $form['sort']['settings']['direction'] = [
266 267 268
          '#type' => 'select',
          '#title' => $this->t('Sort direction'),
          '#required' => TRUE,
269
          '#options' => [
270 271
            'ASC' => $this->t('Ascending'),
            'DESC' => $this->t('Descending'),
272
          ],
273
          '#default_value' => $configuration['sort']['direction'],
274
        ];
275 276 277
      }
    }

278
    $form['auto_create'] = [
279 280
      '#type' => 'checkbox',
      '#title' => $this->t("Create referenced entities if they don't already exist"),
281
      '#default_value' => $configuration['auto_create'],
282
      '#weight' => -2,
283
    ];
284 285

    if ($entity_type->hasKey('bundle')) {
286
      $bundles = array_intersect_key($bundle_options, array_filter((array) $configuration['target_bundles']));
287 288 289 290
      $form['auto_create_bundle'] = [
        '#type' => 'select',
        '#title' => $this->t('Store new items in'),
        '#options' => $bundles,
291
        '#default_value' => $configuration['auto_create_bundle'],
292 293 294 295 296 297 298 299 300 301
        '#access' => count($bundles) > 1,
        '#states' => [
          'visible' => [
            ':input[name="settings[handler_settings][auto_create]"]' => ['checked' => TRUE],
          ],
        ],
        '#weight' => -1,
      ];
    }

302 303 304 305 306 307 308
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
309 310
    parent::validateConfigurationForm($form, $form_state);

311 312 313 314 315 316 317
    // If no checkboxes were checked for 'target_bundles', store NULL ("all
    // bundles are referenceable") rather than empty array ("no bundle is
    // referenceable" - typically happens when all referenceable bundles have
    // been deleted).
    if ($form_state->getValue(['settings', 'handler_settings', 'target_bundles']) === []) {
      $form_state->setValue(['settings', 'handler_settings', 'target_bundles'], NULL);
    }
318 319 320 321

    // Don't store the 'target_bundles_update' button value into the field
    // config settings.
    $form_state->unsetValue(['settings', 'handler_settings', 'target_bundles_update']);
322 323
  }

324 325 326 327 328 329 330 331
  /**
   * Form element validation handler; Filters the #value property of an element.
   */
  public static function elementValidateFilter(&$element, FormStateInterface $form_state) {
    $element['#value'] = array_filter($element['#value']);
    $form_state->setValueForElement($element, $element['#value']);
  }

332 333 334 335
  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
336
    $target_type = $this->getConfiguration()['target_type'];
337 338 339 340 341 342 343 344 345

    $query = $this->buildEntityQuery($match, $match_operator);
    if ($limit > 0) {
      $query->range(0, $limit);
    }

    $result = $query->execute();

    if (empty($result)) {
346
      return [];
347 348
    }

349
    $options = [];
350
    $entities = $this->entityTypeManager->getStorage($target_type)->loadMultiple($result);
351 352
    foreach ($entities as $entity_id => $entity) {
      $bundle = $entity->bundle();
353
      $options[$bundle][$entity_id] = Html::escape($this->entityRepository->getTranslationFromContext($entity)->label());
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    }

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
    $query = $this->buildEntityQuery($match, $match_operator);
    return $query
      ->count()
      ->execute();
  }

  /**
   * {@inheritdoc}
   */
  public function validateReferenceableEntities(array $ids) {
373
    $result = [];
374 375
    if ($ids) {
      $target_type = $this->configuration['target_type'];
376
      $entity_type = $this->entityTypeManager->getDefinition($target_type);
377 378 379 380 381 382 383 384 385
      $query = $this->buildEntityQuery();
      $result = $query
        ->condition($entity_type->getKey('id'), $ids, 'IN')
        ->execute();
    }

    return $result;
  }

386 387 388 389
  /**
   * {@inheritdoc}
   */
  public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
390
    $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
391 392 393
    $bundle_key = $entity_type->getKey('bundle');
    $label_key = $entity_type->getKey('label');

394
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->create([
395 396
      $bundle_key => $bundle,
      $label_key => $label,
397
    ]);
398 399 400 401 402 403 404 405 406 407 408 409 410

    if ($entity instanceof EntityOwnerInterface) {
      $entity->setOwnerId($uid);
    }

    return $entity;
  }

  /**
   * {@inheritdoc}
   */
  public function validateReferenceableNewEntities(array $entities) {
    return array_filter($entities, function ($entity) {
411 412 413
      $target_bundles = $this->getConfiguration()['target_bundles'];
      if (isset($target_bundles)) {
        return in_array($entity->bundle(), $target_bundles);
414 415 416 417 418
      }
      return TRUE;
    });
  }

419 420 421 422 423 424 425 426 427 428 429 430 431 432
  /**
   * Builds an EntityQuery to get referenceable entities.
   *
   * @param string|null $match
   *   (Optional) Text to match the label against. Defaults to NULL.
   * @param string $match_operator
   *   (Optional) The operation the matching should be done with. Defaults
   *   to "CONTAINS".
   *
   * @return \Drupal\Core\Entity\Query\QueryInterface
   *   The EntityQuery object with the basic conditions and sorting applied to
   *   it.
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
433 434
    $configuration = $this->getConfiguration();
    $target_type = $configuration['target_type'];
435
    $entity_type = $this->entityTypeManager->getDefinition($target_type);
436

437
    $query = $this->entityTypeManager->getStorage($target_type)->getQuery();
438 439 440

    // If 'target_bundles' is NULL, all bundles are referenceable, no further
    // conditions are needed.
441
    if (is_array($configuration['target_bundles'])) {
442 443
      // If 'target_bundles' is an empty array, no bundle is referenceable,
      // force the query to never return anything and bail out early.
444
      if ($configuration['target_bundles'] === []) {
445 446 447 448
        $query->condition($entity_type->getKey('id'), NULL, '=');
        return $query;
      }
      else {
449
        $query->condition($entity_type->getKey('bundle'), $configuration['target_bundles'], 'IN');
450 451 452 453 454 455 456 457 458 459
      }
    }

    if (isset($match) && $label_key = $entity_type->getKey('label')) {
      $query->condition($label_key, $match, $match_operator);
    }

    // Add entity-access tag.
    $query->addTag($target_type . '_access');

460
    // Add the Selection handler for system_query_entity_reference_alter().
461 462 463 464
    $query->addTag('entity_reference');
    $query->addMetaData('entity_reference_selection_handler', $this);

    // Add the sort option.
465 466
    if ($configuration['sort']['field'] !== '_none') {
      $query->sort($configuration['sort']['field'], $configuration['sort']['direction']);
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    }

    return $query;
  }

  /**
   * Helper method: Passes a query to the alteration system again.
   *
   * This allows Entity Reference to add a tag to an existing query so it can
   * ask access control mechanisms to alter it again.
   */
  protected function reAlterQuery(AlterableInterface $query, $tag, $base_table) {
    // Save the old tags and metadata.
    // For some reason, those are public.
    $old_tags = $query->alterTags;
    $old_metadata = $query->alterMetaData;

484
    $query->alterTags = [$tag => TRUE];
485
    $query->alterMetaData['base_table'] = $base_table;
486
    $this->moduleHandler->alter(['query', 'query_' . $tag], $query);
487 488 489 490 491 492 493

    // Restore the tags and metadata.
    $query->alterTags = $old_tags;
    $query->alterMetaData = $old_metadata;
  }

}