Example for hook_query_entityreference_alter()

Last updated on
24 December 2018

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

/**
 * This alter hook, provided by core, and known as hook_query_TAG_alter().
 *
 * In this example we alter the query, to filter values from entity
 * reference field.
 * We join the current query if the field name is 'field_foo', to the
 * 'field_bar' table and add a condition based on the joined table.
 */
function hook_query_entityreference_alter(QueryAlterableInterface $query) {
  $field = $query->getMetadata('field');
  if ($field['field_name'] != 'field_foo') {
    // This is not the field we want to alter.
    return;
  }

  // Get the base table.
  $tables = $query->getTables();
  $base_table = key($tables);

  // Join to the new table.
  $field_bar = field_info_field('field_drawer_type');
  $table_name = _field_sql_storage_tablename($field_bar);
  $query->innerJoin($table_name, 'drawer_type', '%alias.entity_id = ' . $base_table . '.tid');

  // Add conditions.
  $query->condition('drawer_type.field_bar_value', 'baz', '=');
}

Help improve this page

Page status: No known problems

You can: