View source
<?php
namespace Drupal\domain\Plugin\EntityReferenceSelection;
use Drupal\user\Entity\User;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
use Drupal\Core\Form\FormStateInterface;
class DomainSelection extends DefaultSelection {
protected $fieldType = 'editor';
public function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = parent::buildEntityQuery($match, $match_operator);
if ($this->currentUser
->hasPermission('administer domains')) {
return $query;
}
if (!$this->currentUser
->hasPermission('access inactive domains')) {
$query
->condition('status', 1);
}
$info = $query
->getMetaData('entity_reference_selection_handler');
if (!empty($info->configuration['entity'])) {
$context['entity_type'] = $info->configuration['entity']
->getEntityTypeId();
$context['bundle'] = $info->configuration['entity']
->bundle();
$context['field_type'] = $this->fieldType;
$account = User::load($this->currentUser
->id());
$this->moduleHandler
->alter('domain_references', $query, $account, $context);
}
return $query;
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$selection_handler_settings = $this->configuration;
$selection_handler_settings += [
'target_bundles' => NULL,
'sort' => [
'field' => 'weight',
'direction' => 'ASC',
],
'auto_create' => FALSE,
'default_selection' => 'current',
];
$form['target_bundles'] = [
'#type' => 'value',
'#value' => NULL,
];
$fields = [
'weight' => $this
->t('Weight'),
'label' => $this
->t('Name'),
'hostname' => $this
->t('Hostname'),
];
$form['sort']['field'] = [
'#type' => 'select',
'#title' => $this
->t('Sort by'),
'#options' => $fields,
'#ajax' => FALSE,
'#default_value' => $selection_handler_settings['sort']['field'],
];
$form['sort']['direction'] = [
'#type' => 'select',
'#title' => $this
->t('Sort direction'),
'#required' => TRUE,
'#options' => [
'ASC' => $this
->t('Ascending'),
'DESC' => $this
->t('Descending'),
],
'#default_value' => $selection_handler_settings['sort']['direction'],
];
return $form;
}
}