You are here

class EntityFieldQuery in EntityFieldQuery Views Backend 8

Views query plugin for an SQL query.

Plugin annotation


@ViewsQuery(
  id = "entity_field_query",
  title = @Translation("Entity field entity query"),
  help = @Translation("Query will be generated and run using the Drupal database API.")
)

Hierarchy

Expanded class hierarchy of EntityFieldQuery

File

src/Plugin/views/query/EntityFieldQuery.php, line 22

Namespace

Drupal\efq_views\Plugin\views\query
View source
class EntityFieldQuery extends QueryPluginBase {

  /**
   * The EntityQuery object used for the query.
   *
   * @var \Drupal\Core\Entity\Query\QueryInterface
   */
  public $query;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return parent::create($container, $configuration, $plugin_id, $plugin_definition);
  }
  protected function getEntityTypeId() {
    return 'node';
  }

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->query = $this->entityTypeManager
      ->getStorage($this
      ->getEntityTypeId())
      ->getQuery();
    $this->tables = array();

    // An entity type (such as EntityFieldQuery: Node) was selected.
    // We have entity type passed in as base table, prefixed with 'efq_'
    $entity_type = preg_replace('/^efq_/', '', $base_table);
    $this->entity_type = $entity_type;
    $this->query
      ->entityCondition('entity_type', $entity_type);
  }
  function option_definition() {
    $options = parent::option_definition();
    $options['field_language'] = array(
      'default' => '***CURRENT_LANGUAGE***',
    );
    $options['query_tags'] = array(
      'default' => array(),
    );
    return $options;
  }

  /**
   * Show field language settings if the entity type we are querying has
   * field translation enabled.
   * If we are querying multiple entity types, then the settings are shown
   * if at least one entity type has field translation enabled.
   */
  function options_form(&$form, &$form_state) {
    if (isset($this->entity_type)) {
      $entities = array();
      $entities[$this->entity_type] = entity_get_info($this->entity_type);
    }
    else {
      $entities = entity_get_info();
    }
    $has_translation_handlers = FALSE;
    foreach ($entities as $type => $entity_info) {
      if (!empty($entity_info['translation'])) {
        $has_translation_handlers = TRUE;
      }
    }
    if ($has_translation_handlers) {
      $languages = array(
        '***CURRENT_LANGUAGE***' => t("Current user's language"),
        '***DEFAULT_LANGUAGE***' => t("Default site language"),
        LANGUAGE_NONE => t('No language'),
      );
      $languages = array_merge($languages, locale_language_list());
      $form['field_language'] = array(
        '#type' => 'select',
        '#title' => t('Field Language'),
        '#description' => t('All fields which support translations will be displayed in the selected language.'),
        '#options' => $languages,
        '#default_value' => $this->options['field_language'],
      );
    }
    $form['query_tags'] = array(
      '#type' => 'textfield',
      '#title' => t('Query Tags'),
      '#description' => t('If set, these tags will be appended to the query and can be used to identify the query in a module. This can be helpful for altering queries.'),
      '#default_value' => implode(', ', $this->options['query_tags']),
      '#element_validate' => array(
        'views_element_validate_tags',
      ),
    );

    // The function views_element_validate_tags() is defined here.
    form_load_include($form_state, 'inc', 'views', 'plugins/views_plugin_query_default');
  }

  /**
   * Special submit handling.
   */
  function options_submit(&$form, &$form_state) {
    $element = array(
      '#parents' => array(
        'query',
        'options',
        'query_tags',
      ),
    );
    $value = explode(',', drupal_array_get_nested_value($form_state['values'], $element['#parents']));
    $value = array_filter(array_map('trim', $value));
    form_set_value($element, $value, $form_state);
  }

  /**
   * Builds the necessary info to execute the query.
   */
  function build(&$view) {
    $view
      ->init_pager($view);

    // Let the pager modify the query to add limits.
    $this->pager
      ->query();
    $count_query = clone $this->query;
    $count_query
      ->count(true);
    $view->build_info['efq_query'] = $this->query;
    $view->build_info['count_query'] = $count_query;
  }

  /**
   * This is used by the style row plugins for node view and comment view.
   */
  function add_field($base_table, $base_field) {
    return $base_field;
  }

  /**
   * This is used by the field field handler.
   */
  function ensure_table($table) {
    return $table;
  }

  /**
   * Executes the query and fills the associated view object with according
   * values.
   *
   * Values to set: $view->result, $view->total_rows, $view->execute_time,
   * $view->pager['current_page'].
   */
  function execute(&$view) {
    $query = $view->build_info['efq_query'];
    $count_query = $view->build_info['count_query'];
    $args = $view->build_info['query_args'];
    $query
      ->addMetaData('view', $view);
    $count_query
      ->addMetaData('view', $view);

    // Add the query tags.
    if (!empty($this->options['query_tags'])) {
      foreach ($this->options['query_tags'] as $tag) {
        $query
          ->addTag($tag);
        $count_query
          ->addTag($tag);
      }
    }
    $start = microtime(true);

    // Determine if the query entity type is local or remote.
    $remote = FALSE;
    $entity_controller = entity_get_controller($this->entity_type);
    if (module_exists('remote_entity') && is_a($entity_controller, 'RemoteEntityAPIDefaultController')) {

      // We're dealing with a remote entity so get the fully loaded list of
      // entities from its query class instead of EntityFieldQuery.
      $remote = TRUE;
      $remote_query = $entity_controller
        ->getRemoteEntityQuery();
      $remote_query
        ->buildFromEFQ($query);
      $remote_entities = $entity_controller
        ->executeRemoteEntityQuery($remote_query);
    }

    // if we are using the pager, calculate the total number of results
    if ($this->pager
      ->use_pager()) {
      try {

        //  Fetch number of pager items differently based on data locality.
        if ($remote) {

          // Count the number of items already received in the remote query.
          $this->pager->total_items = count($remote_entities);
        }
        else {

          /* !$remote */

          // Execute the local count query.
          $this->pager->total_items = $count_query
            ->execute();
        }
        if (!empty($this->pager->options['offset'])) {
          $this->pager->total_items -= $this->pager->options['offset'];
        }
        $this->pager
          ->update_page_info();
      } catch (Exception $e) {
        if (!empty($view->simpletest)) {
          throw $e;
        }

        // Show the full exception message in Views admin.
        if (!empty($view->live_preview)) {
          drupal_set_message($e
            ->getMessage(), 'error');
        }
        else {
          vpr('Exception in @human_name[@view_name]: @message', array(
            '@human_name' => $view->human_name,
            '@view_name' => $view->name,
            '@message' => $e
              ->getMessage(),
          ));
        }
        return;
      }
    }

    // Let the pager set limit and offset.
    $this->pager
      ->pre_execute($query, $args);
    if (!empty($this->limit) || !empty($this->offset)) {

      // We can't have an offset without a limit, so provide a very large limit instead.
      $limit = intval(!empty($this->limit) ? $this->limit : 999999);
      $offset = intval(!empty($this->offset) ? $this->offset : 0);

      // Set the range for the query.
      if ($remote) {

        // The remote query was already executed so slice the results as necessary.
        $remote_entities = array_slice($remote_entities, $offset, $limit, TRUE);
      }
      else {

        /* !$remote */

        // Set the range on the local query.
        $query
          ->range($offset, $limit);
      }
    }
    $view->result = array();
    try {

      // Populate the result array.
      if ($remote) {

        // Give each entity its ID and add it to the result array.
        foreach ($remote_entities as $entity_id => $entity) {
          $entity->entity_id = $entity_id;
          $entity->entity_type = $this->entity_type;
          $view->result[] = $entity;
        }
      }
      else {

        /* !$remote */

        // Execute the local query.
        $results = $query
          ->execute();

        // Load each entity, give it its ID, and then add to the result array.
        foreach ($results as $entity_type => $ids) {

          // This is later used for field rendering
          foreach (entity_load($entity_type, array_keys($ids)) as $entity_id => $entity) {
            $entity->entity_id = $entity_id;
            $entity->entity_type = $entity_type;
            $view->result[] = $entity;
          }
        }
      }
      $this->pager
        ->post_execute($view->result);
      if ($this->pager
        ->use_pager()) {
        $view->total_rows = $this->pager
          ->get_total_items();
      }
    } catch (Exception $e) {

      // Show the full exception message in Views admin.
      if (!empty($view->live_preview)) {
        drupal_set_message($e
          ->getMessage(), 'error');
      }
      else {
        vpr('Exception in @human_name[@view_name]: @message', array(
          '@human_name' => $view->human_name,
          '@view_name' => $view->name,
          '@message' => $e
            ->getMessage(),
        ));
      }
      return;
    }
    $view->execute_time = microtime(true) - $start;
  }
  function get_result_entities($results, $relationship = NULL) {
    $entity = reset($results);
    return array(
      $entity->entity_type,
      $results,
    );
  }
  function add_selector_orderby($selector, $order = 'ASC') {
    $views_data = views_fetch_data($this->base_table);
    $sort_data = $views_data[$selector]['sort'];
    switch ($sort_data['handler']) {
      case 'efq_views_handler_sort_entity':
        $this->query
          ->entityOrderBy($selector, $order);
        break;
      case 'efq_views_handler_sort_property':
        $this->query
          ->propertyOrderBy($selector, $order);
        break;
      case 'efq_views_handler_sort_field':
        $this->query
          ->fieldOrderBy($sort_data['field_name'], $sort_data['field'], $order);
        break;
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityFieldQuery::$entityTypeManager protected property The entity type manager.
EntityFieldQuery::$query public property The EntityQuery object used for the query.
EntityFieldQuery::add_field function This is used by the style row plugins for node view and comment view.
EntityFieldQuery::add_selector_orderby function
EntityFieldQuery::build function Builds the necessary info to execute the query. Overrides QueryPluginBase::build
EntityFieldQuery::create public static function Creates an instance of the plugin. Overrides PluginBase::create
EntityFieldQuery::ensure_table function This is used by the field field handler.
EntityFieldQuery::execute function Executes the query and fills the associated view object with according values. Overrides QueryPluginBase::execute
EntityFieldQuery::getEntityTypeId protected function
EntityFieldQuery::get_result_entities function
EntityFieldQuery::init public function Initialize the plugin. Overrides PluginBase::init
EntityFieldQuery::options_form function Show field language settings if the entity type we are querying has field translation enabled. If we are querying multiple entity types, then the settings are shown if at least one entity type has field translation enabled.
EntityFieldQuery::options_submit function Special submit handling.
EntityFieldQuery::option_definition function
EntityFieldQuery::__construct public function Constructs a PluginBase object. Overrides PluginBase::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$definition public property Plugins's definition
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. 8
PluginBase::$view public property The top object of a view. 1
PluginBase::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides ViewsPluginInterface::buildOptionsForm 16
PluginBase::defineOptions protected function Information about options for all kinds of purposes will be held here. 18
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::destroy public function Clears a plugin. Overrides ViewsPluginInterface::destroy 2
PluginBase::doFilterByDefinedOptions protected function Do the work to filter out stored options depending on the defined options.
PluginBase::filterByDefinedOptions public function Filter out stored options depending on the defined options. Overrides ViewsPluginInterface::filterByDefinedOptions
PluginBase::getAvailableGlobalTokens public function Returns an array of available token replacements. Overrides ViewsPluginInterface::getAvailableGlobalTokens
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::getProvider public function Returns the plugin provider. Overrides ViewsPluginInterface::getProvider
PluginBase::getRenderer protected function Returns the render API renderer. 1
PluginBase::globalTokenForm public function Adds elements for available core tokens to a form. Overrides ViewsPluginInterface::globalTokenForm
PluginBase::globalTokenReplace public function Returns a string with any core tokens replaced. Overrides ViewsPluginInterface::globalTokenReplace
PluginBase::INCLUDE_ENTITY constant Include entity row languages when listing languages.
PluginBase::INCLUDE_NEGOTIATED constant Include negotiated languages when listing languages.
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::listLanguages protected function Makes an array of languages, optionally including special languages.
PluginBase::pluginTitle public function Return the human readable name of the display. Overrides ViewsPluginInterface::pluginTitle
PluginBase::preRenderAddFieldsetMarkup public static function Moves form elements into fieldsets for presentation purposes. Overrides ViewsPluginInterface::preRenderAddFieldsetMarkup
PluginBase::preRenderFlattenData public static function Flattens the structure of form elements. Overrides ViewsPluginInterface::preRenderFlattenData
PluginBase::queryLanguageSubstitutions public static function Returns substitutions for Views queries for languages.
PluginBase::setOptionDefaults protected function Fills up the options of the plugin with defaults.
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. Overrides ViewsPluginInterface::themeFunctions 1
PluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks 6
PluginBase::unpackOptions public function Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away. Overrides ViewsPluginInterface::unpackOptions
PluginBase::usesOptions public function Returns the usesOptions property. Overrides ViewsPluginInterface::usesOptions 8
PluginBase::validate public function Validate that the plugin is correct and can be saved. Overrides ViewsPluginInterface::validate 6
PluginBase::viewsTokenReplace protected function Replaces Views' tokens in a given string. The resulting string will be sanitized with Xss::filterAdmin. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
QueryPluginBase::$limit protected property Stores the limit of items that should be requested in the query.
QueryPluginBase::$pager public property A pager plugin that should be provided by the display.
QueryPluginBase::addSignature public function Add a signature to the query, if such a thing is feasible. 1
QueryPluginBase::alter public function Let modules modify the query just prior to finalizing it. 1
QueryPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides PluginBase::calculateDependencies 1
QueryPluginBase::getAggregationInfo public function Get aggregation info for group by queries. 1
QueryPluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
QueryPluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 1
QueryPluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 1
QueryPluginBase::getDateField public function Returns a Unix timestamp to database native timestamp expression. 1
QueryPluginBase::getDateFormat public function Creates cross-database date formatting. 1
QueryPluginBase::getEntityTableInfo public function Returns an array of all tables from the query that map to an entity type.
QueryPluginBase::getLimit public function Returns the limit of the query.
QueryPluginBase::getTimezoneOffset public function Get the timezone offset in seconds.
QueryPluginBase::loadEntities public function Loads all entities contained in the passed-in $results. . If the entity belongs to the base table, then it gets stored in $result->_entity. Otherwise, it gets stored in $result->_relationship_entities[$relationship_id]; 1
QueryPluginBase::query public function Generate a query and a countquery from all of the information supplied to the object. Overrides PluginBase::query 1
QueryPluginBase::setFieldTimezoneOffset public function Applies a timezone offset to the given field. 2
QueryPluginBase::setGroupOperator public function Control how all WHERE and HAVING groups are put together.
QueryPluginBase::setLimit public function Set a LIMIT on the query, specifying a maximum number of results.
QueryPluginBase::setOffset public function Set an OFFSET on the query, specifying a number of results to skip
QueryPluginBase::setupTimezone public function Set the database to the current user timezone. 1
QueryPluginBase::setWhereGroup public function Create a new grouping for the WHERE or HAVING clause.
QueryPluginBase::submitOptionsForm public function Handle any special handling on the validate form. Overrides PluginBase::submitOptionsForm 1
QueryPluginBase::summaryTitle public function Returns the summary of the settings in the display. Overrides PluginBase::summaryTitle
QueryPluginBase::validateOptionsForm public function Validate the options form. Overrides PluginBase::validateOptionsForm
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.