Saturday, 17 September 2011

How do you expose your legacy database tables to views in drupal 6 Part 2

Continuing from Part 1 of the post where we defined custom data table to make drupal aware of our legacy data, we also want to define custom filters that can be used by the views system to define conditional views.

in the hook_views_data() or our example code in part one, the candidate_views_data() function you can see that a field was defined as below:

    $data['candidate']['candidate_gender'] = array(
        'title' => t('Gender'),
        'field' => array(
          'click sortable' => TRUE,
        'filter' => array(
            'handler' => 'candidate_handler_filter_gender',

notice the filter key in the $data array, we want custom data to appear here, for example 'Male' and 'Female', so we have defined a custom handler by the name 'candidate_handler_filter_gender'.

to make drupal aware of your handler, you need to define them in hook_views_handlers() the definition will look something like this.

function candidate_views_handlers(){
    return array(
      'info' => array(
          'path' => drupal_get_path('module','candidate'). '/views',

      'handlers' => array(
          'candidate_handler_filter_gender' => array(
              'parent' => 'views_handler_filter_string',

having defined this handler, now you need to place a new file called in the earlier defined views sub folder. and the code that goes in this file is:

class candidate_handler_filter_gender extends views_handler_filter_string{
    function value_form(&$form, &$form_state) {

    $form['value'] = array(
    '#type' => 'select',
    '#title' => t('Gender'),
    '#options' => getGender(),

    return $form;


getGender() is a function that just returns a keyed array for 'M'=>'Male', 'F'=>'Female'.

Thats all, now your views interface should hook into your custom module and be aware of the tables, and custom handlers available. 

Remember to clear caches if something does not appear.

No comments:

Post a comment

Using Wodby (drupal4docker) to create our local development environment.

Using Wodby  to create a Drupal local development environment using docker. I have used the official Drupal ...