Drupal views 2 API allows creating views based on any table. Most of the fields you will be displaying will be based on the table columns but it may sometimes be handy to create a non-database field. Usually it will be a field that you need to compute – maybe based on some other fields from the same table. The point is that the field name will not map to the table’s column name.

I will illustrate it on the example below. Let’s say we have a very simple table named distros that hold Linux-based distributions with just 2 columns:

  • id – the primary key
  • name – name of the distribution

I have created a new module called distros with two files:

  • distros.module with function distros_views_api
  • distros.views.inc

In distros.views.inc we need to describe our table – it’s easy for the table columns like name:

function distros_views_data() {
  $data = array();
  $data['distros']['table'] = array(
    'group' => 'distros',
    'title' => 'title',
    'help' => 'help'
  );
  $data['distros']['table']['base'] = array(
    'field' => 'id',
    'title' => 'Distro',
    'help' => 'This is distro main table',
  );
  $data['distros']['name'] = array(
  'field' => array(
    'title' => 'distro name',
    'help' => 'This is distro main table',
  ),
  );
  return $data;
}
To add non-database field, we will need a custom field handler. Otherwise Drupal will try to add field name into SELECT clause it’s using – that will obviously cause an error as the column doesn’t exist. Let’s say we want our view to display a quote from Linus Torvalds. Our new, “virtual” field should be named quote and should always display a text: Talk is cheap. Show me the code. We will call our handler distros_handler_field_distro_quote and overwrite two functions:

  • render – to always display our text
  • query – to prevent Drupal from querying for quote field

In distros_handler_field_distro_quote.inc :

<?php
class distros_handler_field_distro_quote extends views_handler_field {
  function render() {
    return "Talk is cheap. Show me the code.";
  }
  function query() {
    ensure_my_table();
    $this->add_additional_fields();
  }
}

Now, let’s go back to distros.views.inc and register our new handler:

function distros_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'distros'),
    ),
  'handlers' => array(
    'distros_handler_field_distro_quote' => array(
      'parent' => 'views_handler_field',
    ),
  ),
);
}

And finally describe new field by adding to distros_views_data:

$data['distros']['quote'] = array(
  'field' => array(
    'title' => 'Quote from Linus',
    'help' => 'This is non-database field',
    'handler' => 'distros_handler_field_distro_quote',
  ),
);

Install your new module and create the view, here is the final effect:

Drupal view with custom field

Drupal view with custom field

Download the full source code if you wish.