You are on page 1of 1

Drupal: How to create a custom exposed filter in views 3 in Drupal 7

There's a module that provides some examples here: https://www.drupal.org/project


/views_plugin_examples. It's limited but has an exposed filter example. General discussion
here: https://api.drupal.org/api/views/views.api.php/group/views_plugins/7
In broad outline:
1. Create a custom module, with a subdirectory called "views"
2. In your .info file, add a line: files[] = views/MODULE_handler_filter_FILTERNAME.inc
(your filter will never show up if you forget this).
3. In the .module file, add an implementation of hook_views_api():
function MODULE_views_api() {
return array(
'api' => 3,
'path' => drupal_get_path('module', 'MODULE') . '/views',
);
}

4. Within the views subdirectory, you will need to create two files, MODULE.views.inc and
MODULE_handler_filter_FILTERNAME.inc
5. In MODULE.views.inc, you will need to implement either hook_views_data_alter() (for a
new filter on an existing entity type that already has views integration, which is more
common) or hook_views_data() (to provide views integration for your custom entity,
including filters). API documentation is available for both functions. A quick example:
function MODULE_views_data_alter(&$data) {
if ( isset($data['users']) && !isset($data['users']['FILTERNAME']) ) {
$data['users']['FILTERNAME'] = array(
'real field' => 'uid', // name of entity field to which filter applies
'title' => t('HUMAN READABLE NAME OF FILTER'),
'help' => t('HELP TEXT'),
'filter' => array(
'handler' => 'MODULE_handler_filter_FILTERNAME',
),
);
}
}

6. All of the real work happens in MODULE_handler_filter_FILTERNAME.inc. This file defines


a new class that implements your filter, class MODULE_handler_filter_FILTERNAME. You
will usually want to extend one of the existing views filter handler classes to get the
benefit of existing code. These may be found in the "handlers" subdirectory of the views
directory, and also in several of the subdirectories of the "modules" subdirectory. The
views filter handlers you find there are the best documentation for how to implement a
filter, as well as how to extend an existing filter, and you should read through them.
Normally your custom filter class will a) add fields to the extended filter's settings form,
b) in the case of an exposed filter, modifying the exposed widget, and then c)
implementing a query() method that does the real work, based on the saved settings and
input from the exposed widget.

1 of 1

You might also like