Community Documentation

Example for hook_query_entityreference_alter()

Last updated September 20, 2012. Created by Amitaibu on September 20, 2012.
Log in to edit this page.

<?php
/**
* 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', '=');
}
?>

Comments

I'm trying to filter the

I'm trying to filter the entity suggested in the step of adding content, how can I do?
This function does not seem to go ...

thanks

About this page

Drupal version
Drupal 7.x
Audience
Programmers
Level
Intermediate

Site Building Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.