Newer
Older
Dries Buytaert
committed
<?php
Alex Pott
committed
namespace Drupal\views\Plugin\EntityReferenceSelection;
Dries Buytaert
committed
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginBase;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionTrait;
Dries Buytaert
committed
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
Alex Pott
committed
use Drupal\Core\Url;
catch
committed
use Drupal\views\Views;
Dries Buytaert
committed
/**
* Plugin implementation of the 'selection' entity_reference.
*
Alex Pott
committed
* @EntityReferenceSelection(
Dries Buytaert
committed
* id = "views",
* label = @Translation("Views: Filter by an entity reference view"),
* group = "views",
* weight = 0
* )
*/
class ViewsSelection extends SelectionPluginBase implements ContainerFactoryPluginInterface {
use SelectionTrait;
/**
* The loaded View object.
*
Lee Rowlands
committed
* @var \Drupal\views\ViewExecutable
*/
protected $view;
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'view' => [
'view_name' => NULL,
'display_name' => NULL,
'arguments' => [],
],
] + parent::defaultConfiguration();
}
Dries Buytaert
committed
/**
Alex Pott
committed
* {@inheritdoc}
Dries Buytaert
committed
*/
Alex Pott
committed
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$view_settings = $this->getConfiguration()['view'];
catch
committed
$displays = Views::getApplicableViews('entity_reference_display');
Dries Buytaert
committed
// Filter views that list the entity type we want, and group the separate
// displays by view.
Alex Pott
committed
$entity_type = $this->entityManager->getDefinition($this->configuration['target_type']);
$view_storage = $this->entityManager->getStorage('view');
$options = [];
Dries Buytaert
committed
foreach ($displays as $data) {
list($view_id, $display_id) = $data;
$view = $view_storage->load($view_id);
if (in_array($view->get('base_table'), [$entity_type->getBaseTable(), $entity_type->getDataTable()])) {
$display = $view->get('display');
$options[$view_id . ':' . $display_id] = $view_id . ' - ' . $display[$display_id]['display_title'];
Dries Buytaert
committed
}
}
// The value of the 'view_and_display' select below will need to be split
// into 'view_name' and 'view_display' in the final submitted values, so
// we massage the data at validate time on the wrapping element (not
// ideal).
$form['view']['#element_validate'] = [[get_called_class(), 'settingsFormValidate']];
Dries Buytaert
committed
if ($options) {
$default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
$form['view']['view_and_display'] = [
Dries Buytaert
committed
'#type' => 'select',
Alex Pott
committed
'#title' => $this->t('View used to select the entities'),
Dries Buytaert
committed
'#required' => TRUE,
'#options' => $options,
'#default_value' => $default,
Alex Pott
committed
'#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>',
];
Dries Buytaert
committed
$default = !empty($view_settings['arguments']) ? implode(', ', $view_settings['arguments']) : '';
$form['view']['arguments'] = [
Dries Buytaert
committed
'#type' => 'textfield',
Alex Pott
committed
'#title' => $this->t('View arguments'),
Dries Buytaert
committed
'#default_value' => $default,
'#required' => FALSE,
Alex Pott
committed
'#description' => $this->t('Provide a comma separated list of arguments to pass to the view.'),
];
Dries Buytaert
committed
}
else {
if ($this->currentUser->hasPermission('administer views') && $this->moduleHandler->moduleExists('views_ui')) {
$form['view']['no_view_help'] = [
'#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>.', [
':create' => Url::fromRoute('views_ui.add')->toString(),
':existing' => Url::fromRoute('entity.view.collection')->toString(),
]) . '</p>',
];
}
else {
$form['view']['no_view_help']['#markup'] = '<p>' . $this->t('No eligible views were found.') . '</p>';
}
Dries Buytaert
committed
}
return $form;
}
/**
* Initializes a view.
*
* @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".
* @param int $limit
* Limit the query to a given number of items. Defaults to 0, which
* indicates no limiting.
* @param array|null $ids
* Array of entity IDs. Defaults to NULL.
*
* @return bool
* Return TRUE if the view was initialized, FALSE otherwise.
*/
protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
$view_name = $this->getConfiguration()['view']['view_name'];
$display_name = $this->getConfiguration()['view']['display_name'];
Dries Buytaert
committed
// Check that the view is valid and the display still exists.
catch
committed
$this->view = Views::getView($view_name);
Dries Buytaert
committed
if (!$this->view || !$this->view->access($display_name)) {
\Drupal::messenger()->addWarning(t('The reference view %view_name cannot be found.', ['%view_name' => $view_name]));
Dries Buytaert
committed
return FALSE;
}
$this->view->setDisplay($display_name);
// Pass options to the display handler to make them available later.
$entity_reference_options = [
Dries Buytaert
committed
'match' => $match,
'match_operator' => $match_operator,
'limit' => $limit,
'ids' => $ids,
];
Dries Buytaert
committed
$this->view->displayHandlers->get($display_name)->setOption('entity_reference_options', $entity_reference_options);
return TRUE;
}
/**
Alex Pott
committed
* {@inheritdoc}
Dries Buytaert
committed
*/
public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$display_name = $this->getConfiguration()['view']['display_name'];
$arguments = $this->getConfiguration()['view']['arguments'];
$result = [];
Dries Buytaert
committed
if ($this->initializeView($match, $match_operator, $limit)) {
// Get the results.
$result = $this->view->executeDisplay($display_name, $arguments);
}
$return = [];
Dries Buytaert
committed
if ($result) {
foreach ($this->view->result as $row) {
Dries Buytaert
committed
$entity = $row->_entity;
$return[$entity->bundle()][$entity->id()] = $entity->label();
}
}
return $return;
}
/**
Alex Pott
committed
* {@inheritdoc}
Dries Buytaert
committed
*/
public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
$this->getReferenceableEntities($match, $match_operator);
return $this->view->pager->getTotalItems();
Dries Buytaert
committed
}
/**
Alex Pott
committed
* {@inheritdoc}
Dries Buytaert
committed
*/
public function validateReferenceableEntities(array $ids) {
$display_name = $this->getConfiguration()['view']['display_name'];
$arguments = $this->getConfiguration()['view']['arguments'];
$result = [];
Dries Buytaert
committed
if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
// Get the results.
$entities = $this->view->executeDisplay($display_name, $arguments);
$result = array_keys($entities);
}
return $result;
}
/**
* Element validate; Check View is valid.
*/
public static function settingsFormValidate($element, FormStateInterface $form_state, $form) {
Dries Buytaert
committed
// Split view name and display name from the 'view_and_display' value.
if (!empty($element['view_and_display']['#value'])) {
list($view, $display) = explode(':', $element['view_and_display']['#value']);
}
else {
$form_state->setError($element, t('The views entity selection mode requires a view.'));
Dries Buytaert
committed
return;
}
// Explode the 'arguments' string into an actual array. Beware, explode()
// turns an empty string into an array with one empty string. We'll need an
// empty array instead.
$arguments_string = trim($element['arguments']['#value']);
if ($arguments_string === '') {
$arguments = [];
Dries Buytaert
committed
}
else {
// array_map() is called to trim whitespaces from the arguments.
$arguments = array_map('trim', explode(',', $arguments_string));
}
$value = ['view_name' => $view, 'display_name' => $display, 'arguments' => $arguments];
Alex Pott
committed
$form_state->setValueForElement($element, $value);
Dries Buytaert
committed
}
Alex Pott
committed