View source  
  <?php
namespace Drupal\views\Plugin\EntityReferenceSelection;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\views\Views;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ViewsSelection extends PluginBase implements SelectionInterface, ContainerFactoryPluginInterface {
  
  protected $entityManager;
  
  protected $moduleHandler;
  
  protected $currentUser;
  
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityManager = $entity_manager;
    $this->moduleHandler = $module_handler;
    $this->currentUser = $current_user;
  }
  
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity.manager'), $container
      ->get('module_handler'), $container
      ->get('current_user'));
  }
  
  protected $view;
  
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $selection_handler_settings = $this->configuration['handler_settings'];
    $view_settings = !empty($selection_handler_settings['view']) ? $selection_handler_settings['view'] : array();
    $displays = Views::getApplicableViews('entity_reference_display');
    
    $entity_type = $this->entityManager
      ->getDefinition($this->configuration['target_type']);
    $view_storage = $this->entityManager
      ->getStorage('view');
    $options = array();
    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'];
      }
    }
    
    $form['view']['#element_validate'] = array(
      array(
        get_called_class(),
        'settingsFormValidate',
      ),
    );
    if ($options) {
      $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
      $form['view']['view_and_display'] = array(
        '#type' => 'select',
        '#title' => $this
          ->t('View used to select the entities'),
        '#required' => TRUE,
        '#options' => $options,
        '#default_value' => $default,
        '#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>',
      );
      $default = !empty($view_settings['arguments']) ? implode(', ', $view_settings['arguments']) : '';
      $form['view']['arguments'] = array(
        '#type' => 'textfield',
        '#title' => $this
          ->t('View arguments'),
        '#default_value' => $default,
        '#required' => FALSE,
        '#description' => $this
          ->t('Provide a comma separated list of arguments to pass to the view.'),
      );
    }
    else {
      if ($this->currentUser
        ->hasPermission('administer views') && $this->moduleHandler
        ->moduleExists('views_ui')) {
        $form['view']['no_view_help'] = array(
          '#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>.', array(
            ':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>';
      }
    }
    return $form;
  }
  
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
  }
  
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
  }
  
  protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
    $handler_settings = $this->configuration['handler_settings'];
    $view_name = $handler_settings['view']['view_name'];
    $display_name = $handler_settings['view']['display_name'];
    
    $this->view = Views::getView($view_name);
    if (!$this->view || !$this->view
      ->access($display_name)) {
      drupal_set_message(t('The reference view %view_name cannot be found.', array(
        '%view_name' => $view_name,
      )), 'warning');
      return FALSE;
    }
    $this->view
      ->setDisplay($display_name);
    
    $entity_reference_options = array(
      'match' => $match,
      'match_operator' => $match_operator,
      'limit' => $limit,
      'ids' => $ids,
    );
    $this->view->displayHandlers
      ->get($display_name)
      ->setOption('entity_reference_options', $entity_reference_options);
    return TRUE;
  }
  
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $handler_settings = $this->configuration['handler_settings'];
    $display_name = $handler_settings['view']['display_name'];
    $arguments = $handler_settings['view']['arguments'];
    $result = array();
    if ($this
      ->initializeView($match, $match_operator, $limit)) {
      
      $result = $this->view
        ->executeDisplay($display_name, $arguments);
    }
    $return = array();
    if ($result) {
      foreach ($this->view->result as $row) {
        $entity = $row->_entity;
        $return[$entity
          ->bundle()][$entity
          ->id()] = $entity
          ->label();
      }
    }
    return $return;
  }
  
  public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
    $this
      ->getReferenceableEntities($match, $match_operator);
    return $this->view->pager
      ->getTotalItems();
  }
  
  public function validateReferenceableEntities(array $ids) {
    $handler_settings = $this->configuration['handler_settings'];
    $display_name = $handler_settings['view']['display_name'];
    $arguments = $handler_settings['view']['arguments'];
    $result = array();
    if ($this
      ->initializeView(NULL, 'CONTAINS', 0, $ids)) {
      
      $entities = $this->view
        ->executeDisplay($display_name, $arguments);
      $result = array_keys($entities);
    }
    return $result;
  }
  
  public static function settingsFormValidate($element, FormStateInterface $form_state, $form) {
    
    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.'));
      return;
    }
    
    $arguments_string = trim($element['arguments']['#value']);
    if ($arguments_string === '') {
      $arguments = array();
    }
    else {
      
      $arguments = array_map('trim', explode(',', $arguments_string));
    }
    $value = array(
      'view_name' => $view,
      'display_name' => $display,
      'arguments' => $arguments,
    );
    $form_state
      ->setValueForElement($element, $value);
  }
  
  public function entityQueryAlter(SelectInterface $query) {
  }
}