You are here

function data_views_data in Data 7

Same name and namespace in other branches
  1. 8 data.views.inc \data_views_data()
  2. 6 data.views.inc \data_views_data()

Implements hook_views_data().

Dynamically create views integration for any table Data manages.

File

./data.views.inc, line 12
Views hooks and utility functions.

Code

function data_views_data() {
  $data = array();
  $tables = data_get_all_tables();
  foreach ($tables as $table) {

    // Get schema and check wether there are field definitions.
    $schema = $table
      ->get('table_schema');
    $meta = $table
      ->get('meta');
    if (!isset($schema['fields'])) {
      continue;
    }
    $table_data = array();
    $table_data['table'] = array(
      'group' => check_plain($table
        ->get('title')),
    );
    foreach ($schema['fields'] as $field_name => $field) {

      // If there is no label, generate one from field name.
      $title = empty($meta['fields'][$field_name]['label']) ? data_natural_name($field_name) : $meta['fields'][$field_name]['label'];
      $table_data[$field_name] = array(
        'title' => $title,
        'help' => $title,
        'field' => data_get_table_field_views_data('field', $table, $field_name),
        'filter' => data_get_table_field_views_data('filter', $table, $field_name),
        'argument' => data_get_table_field_views_data('argument', $table, $field_name),
        'sort' => data_get_table_field_views_data('sort', $table, $field_name),
      );
    }

    // Tables with a primary key are base tables.
    if (isset($schema['primary key']) && count($schema['primary key']) >= 1) {
      $table_data['table']['base'] = array(
        'field' => current($schema['primary key']),
        'title' => check_plain($table
          ->get('title')),
        'help' => t('Data table'),
        'weight' => 10,
      );
    }

    // Add join information.
    if (isset($meta['join']) && is_array($meta['join'])) {
      $table_data['table']['join'] = array();
      foreach ($meta['join'] as $left_table => $join) {

        // @todo: See if left table has other tables it is linked to and link
        // all the way to the leftmost table.
        $table_data['table']['join'][$left_table] = array(
          'left_field' => $join['left_field'],
          'field' => $join['field'],
          'type' => $join['inner_join'] ? 'INNER' : 'LEFT',
        );

        // Add an explicit relationship for every join added.
        $table_data[$join['field']]['relationship'] = array(
          'label' => "{$table->get('name')}.{$join['field']} -> {$left_table}.{$join['left_field']}",
          'base' => $left_table,
          'base field' => $join['left_field'],
        );
      }
    }
    $data[$table
      ->get('name')] = $table_data;
  }
  return $data;
}