You are here

public function EntityReference::query in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/views/src/Plugin/views/display/EntityReference.php \Drupal\views\Plugin\views\display\EntityReference::query()

Add anything to the query that we might need to.

Overrides DisplayPluginBase::query

File

core/modules/views/src/Plugin/views/display/EntityReference.php, line 149

Class

EntityReference
The plugin that handles an EntityReference display.

Namespace

Drupal\views\Plugin\views\display

Code

public function query() {
  if (!empty($this->view->live_preview)) {
    return;
  }

  // Make sure the id field is included in the results.
  $id_field = $this->view->storage
    ->get('base_field');
  $id_table = $this->view->storage
    ->get('base_table');
  $this->id_field_alias = $this->view->query
    ->addField($id_table, $id_field);
  $options = $this
    ->getOption('entity_reference_options');

  // Restrict the autocomplete options based on what's been typed already.
  if (isset($options['match'])) {
    $style_options = $this
      ->getOption('style');
    $value = $this->connection
      ->escapeLike($options['match']);
    if ($options['match_operator'] !== '=') {
      $value = $value . '%';
      if ($options['match_operator'] != 'STARTS_WITH') {
        $value = '%' . $value;
      }
    }

    // Multiple search fields are OR'd together.
    $conditions = new Condition('OR');

    // Build the condition using the selected search fields.
    foreach ($style_options['options']['search_fields'] as $field_id) {
      if (!empty($field_id)) {

        // Get the table and field names for the checked field.
        $field_handler = $this->view->field[$field_id];
        $table_alias = $this->view->query
          ->ensureTable($field_handler->table, $field_handler->relationship);
        $field_alias = $this->view->query
          ->addField($table_alias, $field_handler->realField);
        $field = $this->view->query->fields[$field_alias];

        // Add an OR condition for the field.
        $conditions
          ->condition($field['table'] . '.' . $field['field'], $value, 'LIKE');
      }
    }
    $this->view->query
      ->addWhere(0, $conditions);
  }

  // Add an IN condition for validation.
  if (!empty($options['ids'])) {
    $this->view->query
      ->addWhere(0, $id_table . '.' . $id_field, $options['ids'], 'IN');
  }
  $this->view
    ->setItemsPerPage($options['limit']);
}