Fresh Blurbs

Drupal: Expose a Custom Field to Views2

Disclaimer: Views2 Advanced Help contains a more detailed and comprehensive documentation on the same subject. However, that also means that you have to actually comprehend more :) This is just a quick sample code of one usage of the hook_views_data() to expose custom fields from a custom table to Views2. If you need more advanced functionality, do refer to Views2 documentation.

Let's say we are building a small job posting board and, for whatever reason, decided to store all resume-related extra fields in a table called "resume", instead of using CCK. Now we need to expose those fields to Views, to use all the beauty and flexibility of the automated query generation provided by Views.

Let's write a custom module called resume (or add it to an existing module).

The very first thing you need to do when you implement Views hooks is to tell Views that you are doing so and (optionally) - where your inc file will rely that holds all views hook implementation routines. We do that using hook_views_api(). Assuming your module is called "resume" and that you want to put views hook implementation file in the "views" subfolder:

function resume_views_api() {
  return array(
    'api' => 2,
    'path' => 
   drupal_get_path('module', 'resume') . '/views',

If you omit the "path" argument, you will have to create the file in the root folder of your module (or "includes" subfolder). If you do indicate path - you create it on that path.

Let's create file (under the "views" fubfolder of the resume module's folder, in our case) and enter following code in it:


function resume_views_data() {
  $data['resume'] = array(
    'table' => array(
      'group' => 'Resume',
      'title' => 'skills',
      'join' => array(
        'node' => array(
          'left_field' => 'nid',
          'field' => 'nid',        
    'skills' => array(
      'title' => t('Skills'),
      'help' => t('Applicant Skills.'), // The help that appears on the UI,
      // Information for displaying the nid
      'field' => array(
        'handler' => 'views_handler_field_node',
        'click sortable' => TRUE,


  return $data;  

this will expose a property called "skills" from the "resume table" as a proper Views2 field that can be used in the Views queries.

That's it. You just created your first custom Views2 field!

Again, Views2 has more flexibility in the hook_views_data() hook, then shown here. Do refer to the documentation (Advanced Help) if you need more.

comments powered by Disqus