View source
<?php
namespace Drupal\Core\Entity\Plugin\EntityReferenceSelection;
use Drupal\Component\Utility\Html;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginBase;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\EntityOwnerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DefaultSelection extends SelectionPluginBase implements ContainerFactoryPluginInterface, SelectionWithAutocreateInterface {
use DeprecatedServicePropertyTrait;
protected $deprecatedProperties = [
'entityManager' => 'entity.manager',
];
protected $entityTypeManager;
protected $entityFieldManager;
public $entityTypeBundleInfo;
protected $entityRepository;
protected $moduleHandler;
protected $currentUser;
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;
}
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'));
}
public function defaultConfiguration() {
return [
'target_bundles' => NULL,
'sort' => [
'field' => '_none',
'direction' => 'ASC',
],
'auto_create' => FALSE,
'auto_create_bundle' => NULL,
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$configuration = $this
->getConfiguration();
$entity_type_id = $configuration['target_type'];
$entity_type = $this->entityTypeManager
->getDefinition($entity_type_id);
$bundles = $this->entityTypeBundleInfo
->getBundleInfo($entity_type_id);
if ($entity_type
->hasKey('bundle')) {
$bundle_options = [];
foreach ($bundles as $bundle_name => $bundle_info) {
$bundle_options[$bundle_name] = $bundle_info['label'];
}
natsort($bundle_options);
$form['target_bundles'] = [
'#type' => 'checkboxes',
'#title' => $entity_type
->getBundleLabel(),
'#options' => $bundle_options,
'#default_value' => (array) $configuration['target_bundles'],
'#required' => TRUE,
'#size' => 6,
'#multiple' => TRUE,
'#element_validate' => [
[
get_class($this),
'elementValidateFilter',
],
],
'#ajax' => TRUE,
'#limit_validation_errors' => [],
];
$form['target_bundles_update'] = [
'#type' => 'submit',
'#value' => $this
->t('Update form'),
'#limit_validation_errors' => [],
'#attributes' => [
'class' => [
'js-hide',
],
],
'#submit' => [
[
EntityReferenceItem::class,
'settingsAjaxSubmit',
],
],
];
}
else {
$form['target_bundles'] = [
'#type' => 'value',
'#value' => [],
];
}
if ($entity_type
->entityClassImplements(FieldableEntityInterface::class)) {
$fields = [];
foreach (array_keys($bundles) as $bundle) {
$bundle_fields = array_filter($this->entityFieldManager
->getFieldDefinitions($entity_type_id, $bundle), function ($field_definition) {
return !$field_definition
->isComputed();
});
foreach ($bundle_fields as $field_name => $field_definition) {
$columns = $field_definition
->getFieldStorageDefinition()
->getColumns();
if (count($columns) > 1) {
foreach ($columns as $column_name => $column_info) {
$fields[$field_name . '.' . $column_name] = $this
->t('@label (@column)', [
'@label' => $field_definition
->getLabel(),
'@column' => $column_name,
]);
}
}
else {
$fields[$field_name] = $this
->t('@label', [
'@label' => $field_definition
->getLabel(),
]);
}
}
}
$form['sort']['field'] = [
'#type' => 'select',
'#title' => $this
->t('Sort by'),
'#options' => $fields,
'#ajax' => TRUE,
'#empty_value' => '_none',
'#sort_options' => TRUE,
'#limit_validation_errors' => [],
'#default_value' => $configuration['sort']['field'],
];
if ($entity_type
->hasKey('bundle')) {
$form['sort']['field']['#states'] = [
'visible' => [
':input[name^="settings[handler_settings][target_bundles]["]' => [
'checked' => TRUE,
],
],
];
}
$form['sort']['settings'] = [
'#type' => 'container',
'#attributes' => [
'class' => [
'entity_reference-settings',
],
],
'#process' => [
[
EntityReferenceItem::class,
'formProcessMergeParent',
],
],
];
if ($configuration['sort']['field'] != '_none') {
$form['sort']['settings']['direction'] = [
'#type' => 'select',
'#title' => $this
->t('Sort direction'),
'#required' => TRUE,
'#options' => [
'ASC' => $this
->t('Ascending'),
'DESC' => $this
->t('Descending'),
],
'#default_value' => $configuration['sort']['direction'],
];
}
}
$form['auto_create'] = [
'#type' => 'checkbox',
'#title' => $this
->t("Create referenced entities if they don't already exist"),
'#default_value' => $configuration['auto_create'],
'#weight' => -2,
];
if ($entity_type
->hasKey('bundle')) {
$bundles = array_intersect_key($bundle_options, array_filter((array) $configuration['target_bundles']));
$form['auto_create_bundle'] = [
'#type' => 'select',
'#title' => $this
->t('Store new items in'),
'#options' => $bundles,
'#default_value' => $configuration['auto_create_bundle'],
'#access' => count($bundles) > 1,
'#states' => [
'visible' => [
':input[name="settings[handler_settings][auto_create]"]' => [
'checked' => TRUE,
],
],
],
'#weight' => -1,
];
}
return $form;
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::validateConfigurationForm($form, $form_state);
if ($form_state
->getValue([
'settings',
'handler_settings',
'target_bundles',
]) === []) {
$form_state
->setValue([
'settings',
'handler_settings',
'target_bundles',
], NULL);
}
$form_state
->unsetValue([
'settings',
'handler_settings',
'target_bundles_update',
]);
}
public static function elementValidateFilter(&$element, FormStateInterface $form_state) {
$element['#value'] = array_filter($element['#value']);
$form_state
->setValueForElement($element, $element['#value']);
}
public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$target_type = $this
->getConfiguration()['target_type'];
$query = $this
->buildEntityQuery($match, $match_operator);
if ($limit > 0) {
$query
->range(0, $limit);
}
$result = $query
->execute();
if (empty($result)) {
return [];
}
$options = [];
$entities = $this->entityTypeManager
->getStorage($target_type)
->loadMultiple($result);
foreach ($entities as $entity_id => $entity) {
$bundle = $entity
->bundle();
$options[$bundle][$entity_id] = Html::escape($this->entityRepository
->getTranslationFromContext($entity)
->label());
}
return $options;
}
public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
$query = $this
->buildEntityQuery($match, $match_operator);
return $query
->count()
->execute();
}
public function validateReferenceableEntities(array $ids) {
$result = [];
if ($ids) {
$target_type = $this->configuration['target_type'];
$entity_type = $this->entityTypeManager
->getDefinition($target_type);
$query = $this
->buildEntityQuery();
$result = $query
->condition($entity_type
->getKey('id'), $ids, 'IN')
->execute();
}
return $result;
}
public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
$entity_type = $this->entityTypeManager
->getDefinition($entity_type_id);
$values = [
$entity_type
->getKey('label') => $label,
];
if ($bundle_key = $entity_type
->getKey('bundle')) {
$values[$bundle_key] = $bundle;
}
$entity = $this->entityTypeManager
->getStorage($entity_type_id)
->create($values);
if ($entity instanceof EntityOwnerInterface) {
$entity
->setOwnerId($uid);
}
return $entity;
}
public function validateReferenceableNewEntities(array $entities) {
return array_filter($entities, function ($entity) {
$target_bundles = $this
->getConfiguration()['target_bundles'];
if (isset($target_bundles)) {
return in_array($entity
->bundle(), $target_bundles);
}
return TRUE;
});
}
protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
$configuration = $this
->getConfiguration();
$target_type = $configuration['target_type'];
$entity_type = $this->entityTypeManager
->getDefinition($target_type);
$query = $this->entityTypeManager
->getStorage($target_type)
->getQuery();
if (is_array($configuration['target_bundles'])) {
if ($configuration['target_bundles'] === []) {
$query
->condition($entity_type
->getKey('id'), NULL, '=');
return $query;
}
else {
$query
->condition($entity_type
->getKey('bundle'), $configuration['target_bundles'], 'IN');
}
}
if (isset($match) && ($label_key = $entity_type
->getKey('label'))) {
$query
->condition($label_key, $match, $match_operator);
}
$query
->addTag($target_type . '_access');
$query
->addTag('entity_reference');
$query
->addMetaData('entity_reference_selection_handler', $this);
if ($configuration['sort']['field'] !== '_none') {
$query
->sort($configuration['sort']['field'], $configuration['sort']['direction']);
}
return $query;
}
protected function reAlterQuery(AlterableInterface $query, $tag, $base_table) {
$old_tags = $query->alterTags;
$old_metadata = $query->alterMetaData;
$query->alterTags = [
$tag => TRUE,
];
$query->alterMetaData['base_table'] = $base_table;
$this->moduleHandler
->alter([
'query',
'query_' . $tag,
], $query);
$query->alterTags = $old_tags;
$query->alterMetaData = $old_metadata;
}
}