Fragmented Thought

Joining Drupal (CCK) Fields To Other Base Tables Through Views

By

Published:

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

Working on a D6 CCK site today, so the code is slightly outdated but can likely be adapted for D7 fields quickly enough. What we had was a seperate system of key levels available to users in the system coming from a custom module. These levels were defined in a table exposed to views through the api previously. Today, we needed to create a field on a node that contained a reference to a level. There was no way to do this directly though views, as our custom base table was a loner. That left two possible options:

Create a simple integer field containing the ids of the key levels as a field on the node, and create the relationship in views after 'somehow'. Create a new type of field 'something' like node reference that pointed back at our levels. While I admin, #2 is the far stronger option for an admin controlling the system manually, that wasn't the case for us this time. The field itself is going to be updated by various events through many parts of the system. Creating a special field type just for this would have been a waste of time since the admin isn't even allowed to edit the field. So, here's how we accomplished number one.

Go ahead and create your integer field. Get it filling in the ids from the other table, then it's time to expose the relationship to views. The core already exposes the node, and it's fields to views, so you have to use the views_data_alter hook to modify the existing field.

/** * Implementation of hook_views_data_alter */ function hook_views_data_alter(&$data){ // Add an extra relationship for field_key_level to key point levels $data['node_data_field_key_level']['field_key_level_value']['relationship'] = array( 'base' => 'uc_key_points_levels', 'field' => 'lid', 'left_field' => 'field_key_level_value', 'handler' => 'views_handler_relationship', 'label' => t('Key Point Level'), ); }