[Drupal] How to add View relationships programmatically with custom database tables in Drupal 7

| | 2 min read

We were faced with a situation in one of our clients Drupal sites where we had to add View relationships programmatically with custom database tables. The site was running on Drupal 7. If you are faced with the same situation in your Drupal website and want to know how to add View relationships programmatically with custom database tables in Drupal 7 then read on to know the solution.

Follow the method below to add View relationships to custom database tables

  • We had the following fields in the custom database table
    • id, type, language, name, created, node_type, entity, entity_id, created_by, source, text, changed, data
  • These custom database tables were already integrated with the View module
  • Now we needed to create a View relationship between the above fields with an existing Drupal field, i.e. between entity and entity_id field in the custom table and a Drupal entity like user, taxonomy and between an entity_id and a Drupal entity id like user_id and node_id
  • We implemented this by using the hook_views_data_alter function as follows
    function hook_views_data_alter(&$data) {
    $entity_info = entity_get_info();
    
      foreach ($entity_info as $entity_type => $info) {
    
        // Note to entity.
        $data[CUSTOM_TABLE_NAME]['CUSTOM_TABLE_NAME_related_' . $entity_type] = array(
          'group' => t(CUSTOM_TABLE_TITLE),
          'title' => t('CUSTOM_TABLE_TITLE to @entity',
            array('@entity' => drupal_ucfirst($info['label']))),
          'help' => t('The @entity entity that is associated with the .',
            array('@entity' => $info['label'])),
          'relationship' => array(
            'handler' => 'views_handler_relationship',
            'label' => t('@entity from CUSTOM_TABLE_TITLE',
              array('@entity' => $entity_type)),
            'base' => $info['base table'],
            'base field' => $info['entity keys']['id'],
            'relationship field' => 'entity_id',
            'extra' => array(
              array('table' => 'CUSTOM_TABLE_NAME', 'field' => 'entity', 'value' => $entity_type),
            ),
          ),
        );
    
      }
  • If you need professional help in customizing databases and views in your Drupal website, get in touch with us