How to implements View's relationships on a custom field?

Strae's picture

Hi guys, I've created a simple custom field (via field api) that should "emulate" references, but allow to define the "reference" type (using a Taxonomy Term).

Basically, I have an entity_type (Company, created with eck module) that use my field to store employees, and the taxonomy term give me the employee type (commercial, owner, secretary, etc...)

I cant put taxonomy term directly in the user, becose a user can be an employee of two different companies.

My custom field schema:

$schema = array(
    'columns' => array(
      'entity_type' => array(
        'type' => 'varchar',
        'length' => '50',
        'not null' => true
      'entity_bundle' => array(
        'type' => 'varchar',
        'length' => '50',
        'not null' => true
      'entity_id' => array(
        'type' => 'int',
        'size' => 'medium',
        'not null' => true
      'tid' => array(
        'type' => 'int',
        'size' => 'medium',
        'not null' => false

My goal is to integrate this field with Views (7-3.x) so that I can use it in relationships.

I've read the source code of entityreference module to understand how it does the trick, my code so far (edited version of entityreference.views hook_field_views_data_views_data_alter()):

function mymodule_field_views_data_views_data_alter(&$data, $field) {
// This is for debugging purpose, my next step is to add the entity_type
  // in the view's relation form
$entity_info = entity_get_info('company');
$data[$entity_info['base table']]['mymoduyle_employee']['relationship'] = array(
'handler' => 'views_handler_relationship_entity_reverse',
'field_name' => $field['field_name'],
'field table' => _field_sql_storage_tablename($field),
'field field' => $field['field_name'] . '_entity_id',
'base' => $entity_info['base table'],
'base field' => $entity_info['entity keys']['id'],
'label' => t('Companies Employee'),
'group' => t('Mymodule'),
'title' => t('Employee of the company.'),
'help' => t('Employee of the company.'),
// I havent understood how to set the join_extra..
'join_extra' => array(
0 => array(
'field' => 'entity_type',
'value' => 'company',
1 => array(
'field' => 'deleted',
'value' => 0,
'numeric' => TRUE,

I guess the query is right, becose I dont get any error; But I dont understand how to "tell" views to handle the relation...


I know it's been over a year

areynolds's picture

I know it's been over a year since this was posted, but for folks looking to do the same thing I'd recommend taking a look at the sample code in the API docs for hook_views_data(). That will teach you how to describe your custom entity's data model to Views so you can create relationships to other Drupal entities (like nodes and users) easily.