Tuesday 25 October 2011

Creating views for custom tables in Drupal 6

At a minimum, if your module wants to use Views, it needs to implement one hook:


function hook_views_data();


This function returns data that will describe how your module's tables relate to the Drupal node table, as well as what fields can be displayed and sorted, and how your tables may be filtered. This hook can return just one or many tables. This function should be placed in a file named MODULENAME.views.inc in your module's directory. Views will automatically find it and include it when necessary.

If you want to provide default views that your users can immediately use, implement hook_views_default_views(). You can use the views exporter tool to create this hook. This hook should be placed in MODULENAME.views_default.inc.

Implementation steps

1.Implement the hook_views_api() in your module.


function MODULENAME_views_api() {
return array(
'api' => 2,
'path' => drupal_get_path('module', 'MODULENAME') . '/modules',
);
}


2. Create a file named MODULENAME.views.inc and put it in your modules diretory.
/sites/all/modules/MODULENAME/modules/MODULENAME.views.inc

3. This .inc file must implement the hook_views_data() and the sample impelemntation is given below.

function custom_views_views_data() {

$data['custom_views']['table']['group'] = t('Custom View');

// Here 'custom_views' will be your table name and this will be treated as base table
$data['custom_views']['table']['base'] = array(
'field' => 'id',
'title' => t('Custom table'),
'help' => t('Stores information about custom table.'),
'weight' => 10,
);
// Following are the fields of the table 'custom_views'
// Field:custom_id
$data['custom_views']['custom_id'] = array(
'title' => t('ID'),
'help' => t('ID of the custom table.'),

'field' => array(
'handler' => 'views_handler_field',
'click sortable' => TRUE,
),
'filter' => array(
'handler' => 'views_handler_filter_string',
),
'argument' => array(
'handler' => 'views_handler_argument_string',
),
'sort' => array(
'handler' => 'views_handler_sort',
),
);

// Field:custom_title
$data['custom_views']['custom_title'] = array(
'title' => t('Name'),
'help' => t('Name of the field.'),

'field' => array(
'handler' => 'views_handler_field',
'click sortable' => TRUE,
),
'filter' => array(
'handler' => 'views_handler_filter_string',
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'argument' => array(
'handler' => 'views_handler_argument_string',
),
);

return $data;

}

Now when you create a new view, the custom fields will be included in the view.

For more information on views2 visit on http://drupal.org/node/235062

1 comment:

laxman said...

G8 r u try this .