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
In distros.views.inc we need to describe our table – it’s easy for the table columns like name:
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 :
Now, let’s go back to distros.views.inc and register our new handler:
And finally describe new field by adding to distros_views_data:
Install your new module and create the view, here is the final effect:
Download the full source code if you wish.