Creating Custom Views Filters With An Exposed Form Element In Drupal 6

20th April 2011 - 5 minutes read time

Views is an amazing module, but sometimes you can come across certain limitations that make life difficult. For example, I created a view that pulled in a bunch of nodes based on different taxonomy terms. The problem was that I had more than one taxonomy term in different vocabularies being used to filter the results, which essentially caused the same field in the term_data table to be used for both taxonomy filters. So, no matter what I changed the parameters to I always received no results. I did try and add the second term as an argument but it isn't possible to do LIKE matches with views arguments.

After a bit of head scratching I decided that I needed to create a custom Views filter for the second element. This would create a second join between the node and the term_data tables and allow me to filter it using a LIKE match. Using this approach made sense as I also wanted the element to be exposed so that a user could enter a search term to restrict the View results. What follows is how to go about setting up custom Views filters along with the associated exposed form elements by using the Views API.

The first thing we need is a implementation of HOOK_views_api() so that Views knows that the module is Views enabled. These function hooks need to be added to a module so you can either use an existing module or create a new one.

  1. /**
  2.  * Implentation of HOO_views_api()
  3.  *
  4.  * @return array An associative array of views options.
  5.  */
  6. function mymodule_views_api() {
  7. return array(
  8. 'api' => 2.0
  9. );
  10. }

Before we can point to our Views filter handlers we must first let Views know where they are by including a HOOK_views_handlers() hook. Here, we are defining a single handler class that will make the needed changes to our query object and add in the form element. Note that the path is set to a directory called views in the current module.

  1. /**
  2.  *
  3.  * Register the views handlers with the view.
  4.  *
  5.  * @return array An associative array of options.
  6.  */
  7. function mymodule_views_handlers() {
  8. return array(
  9. 'info' => array(
  10. 'path' => drupal_get_path('module', 'mymodule') . '/views',
  11. ),
  12. 'handlers' => array(
  13. 'mymodule_special_data_filter_view' => array(
  14. 'parent' => 'views_handler_filter',
  15. ),
  16. ),
  17. );
  18. }

The next thing we need is an implementation of HOOK_views_data(), which will tells Views about all sorts of things, but in this case we will tell Views about our filter. The function should return an associative array of items, each one being a filter that we want to implement. The array can be very large and complex, with table and field definitions, but to keep things simple I have tied in this filter to the node table by using the 'node' element of the $data array. This filter will therefore appear when we go on to create a node View type and will appear in the list of node filters.

The important bit here is the filter element (which tells Views to define a filter) and the filter handler (which will handle what our filter does). The handler element contains the name of a class we created a reference to earlier that will add the extra joins and where clauses to the query.

  1. /**
  2.  * Implementation of HOOK_views_data
  3.  *
  4.  * Tells views about the filters we need to add.
  5.  *
  6.  * @return array An associative array of options.
  7.  */
  8. function mymodule_views_data() {
  9. $data = array();
  10.  
  11. $data['node']['mymodule_special_data'] = array(
  12. 'title' => t('Custom Taxonomy Lookup'),
  13. 'help' => t('Added to create a second link between the node and taxonomy tables.'),
  14. 'filter' => array(
  15. 'handler' => 'mymodule_special_data_filter_view',
  16. ),
  17. );
  18.  
  19. return $data;
  20. }

Create a file called mymodule_special_data_filter_view.inc in your module directory in the views sub folder and define a class called mymodule_special_data_filter_view. This class extends views_handler_filter and defines two methods. The value_form() method is used to create the element for the exposed form widget. The query() method is used to add (or remove) parts of the query in the View.

  1. <?php class mymodule_special_data_filter_view extends views_handler_filter
  2. {
  3. /**
  4.   * Shortcut to display the exposed options form.
  5.   */
  6. function value_form(&$form, &$form_state) {
  7. }
  8.  
  9. /**
  10.   * Change the query.
  11.   */
  12. function query() {
  13. // Ensure table alias has been set
  14. $table_alias = $this-?>ensure_my_table();
  15.  
  16. // Rest of query information goes here
  17. }
  18. }

Essentially, what we are trying to add to the query are the following clauses.

A left join between the term_node and the node tables, using the alias term_node2 for the term_node table.

LEFT JOIN term_node term_node2 ON node.vid = term_node2.vid

A left join between the term_data and the term_data tables, using the alias term_data2 for the term_data table.

LEFT JOIN term_data term_data2 ON term_node2.tid = term_data2.tid

An addition to the WHERE clause to restrict the data being included.

AND (UPPER(term_data2.name) LIKE UPPER('%Term Name%'))

Although it took me a while to actually track down this information, the easiest part of this is creating the form element for the exposed filter. All you need to do is add a method called value_form() and then define the form elements you want to have in your exposed form. The following will create a single text field that we can use to extract our data from.

  1. class mymodule_special_data_filter_view extends views_handler_filter
  2. {
  3. /**
  4.   * Shortcut to display the exposed options form.
  5.   */
  6. function value_form(&$form, &$form_state) {
  7. //$options = menu_parent_options(menu_get_menus(FALSE), 1);
  8.  
  9. $form['value'] = array(
  10. '#type' => 'textfield',
  11. '#title' => t('Term Name'),
  12. '#default_value' => NULL,
  13. );
  14.  
  15. return $form;
  16. }
  17.  
  18. ... SNIP

The final part of this is to add the code to the query() method to change the outputted SQL. I have included lots of comments in the code to clearly explain what is going on. Essentially, if the exposed form has been entered by the user then the value is picked up by this code and the needed joins are added. I also found that I had to add a call to $this->query->add_table() in order to create an alias for the term_node table. If this is left out then the second join is done between term_data2 and term_node, which leaves us back at square one.

  1. function query() {
  2. // Ensure table alias has been set
  3. $table_alias = $this->ensure_my_table();
  4.  
  5. // Get term value
  6. $term_value = check_plain($this->view->exposed_input['mymodule_special_data_filter_view']);
  7.  
  8. // Make sure term value is set.
  9. if ($term_value != '') {
  10. /*
  11.   Query parts to add:
  12.   1. LEFT JOIN term_node term_node2 ON node.vid = term_node2.vid
  13.   2. LEFT JOIN term_data term_data2 ON term_node2.tid = term_data2.tid
  14.   3. AND (UPPER(term_data2.name) LIKE UPPER('%Term Name%'))
  15.   */
  16.  
  17. // Add the term_node table with an alias of term_node2 this ensures
  18. $this->query->add_table('term_node', NULL, NULL, 'term_node2');
  19.  
  20. // Add a join between the term_node and the node tables
  21. // This uses the alias term_node2 for the term_node table
  22. $join = new views_join();
  23. $join->construct('term_node', $this->table_alias, 'vid', 'vid', array(), 'LEFT');
  24. $this->query->ensure_table('term_node2', $this->relationship, $join);
  25.  
  26. // Add a join between the term_data and term_node tables
  27. // This uses the alias term_data2 for the term_data table
  28. $join = new views_join();
  29. $join->construct('term_data', 'term_node2', 'tid', 'tid', array(), 'LEFT');
  30. $return = $this->query->ensure_table('term_data2', $this->relationship, $join);
  31.  
  32. // Add a where clause to the query
  33. $this->query->add_where($this->options['group'], "(UPPER(term_data2.name) LIKE UPPER('%%%s%%')) ", $term_value);
  34. }
  35. }

I have added a check here to make sure that a value exists from the exposed filter for me to use, if it is then I do the query altering, otherwise the code is not run. This might be different for your implementation so you need to check what is going on around this line:

$term_value = check_plain($this->view->exposed_input['mymodule_special_data_filter_view']);

I should note that this code was created specifically for my needs and I include it here as it took me a while to find out about all the needed components. Your Drupal project will almost certainly be different from mine so this code might not do what you want.

Comments

Permalink

Great tutorial.
How to theme such exposed custom filter? I have added custom filters using above technique. Now I am trying to theme this exposed filter. So I have copied views-exposed-form.tpl.php, but some how in foreach($widgets as $id => $widget) --- $widget doesn't hold this exposed filter instead it gets printed in  print $button . Could you please help me to theme filter?

Asif (Tue, 04/26/2011 - 07:55)

Permalink

I'm not sure about that. When I created this view I added the exposed filters in the same way as I normally do and the vews-exposed-form.tpl.php template seems to contain what it should do. Button should only contain the rendered submit button that is created by Views interanlly.

Permalink

I have defined 3 custome filters. 1st holds checkboxes, 2nd holds radio button. For these two filters query function is getting executed and where clause is getting appended. But the 3rd one have textfield and select field, whe trying to submit query function doesn't executed. I tried to debug by echoing the things inside query function but no effect. Could you please tell me what could be wrong?

Asif (Wed, 04/27/2011 - 11:49)

Permalink

I think problem is where filter holds more than one form element. If i define my filter with single text field with following code spec

  1. $key = $this->options['expose']['identifier'];
  2. $form[$key] = array(
  3. '#type' => 'textfield',
  4. '#size' => 15,
  5. '#default_value' => $this->value,
  6. );

It works fine. But if I want to include another form field, then If I changed above code spec to following query function is not getting executed.

  1. $key = $this->options['expose']['identifier'];
  2. $form[$key]['code'] = array(
  3. '#type' => 'textfield',
  4. '#size' => 15,
  5. '#default_value' => $this->value,
  6. );
  7. $form[$key]['cat'] = array(
  8. '#type' => 'select',
  9. '#title' => 'Range',
  10. '#options' => array(
  11. 'a' => t('A'),
  12. 'b' => t('B'),
  13. 'c' => t('C'),
  14. 'd' => t('D'),
  15. ),
  16. '#default_value' => 'a',
  17. );

Asif (Wed, 04/27/2011 - 13:49)

Permalink

This is one of the best tutorials I've ever seen! Thanks so much. One thing I tweaked when I transliterated your code into my files is the line in the quer() function

$term_value = check_plain($this->view->exposed_input['mymodule_special_data_filter_view']);

I changed mine to:

$term_value = check_plain($this->view->exposed_input['mymodule_special_data']);

I'm looking forward to reading your other posts. Awesome job.

Dracolyte (Wed, 07/20/2011 - 01:34)

Permalink

I'm having a similar problem. It seems that a $form['value'] form element is required in order for a value_form with 2+ elements to be submitted correctly. At least when I add a value form element (for a total of 3 form elements in one value_form) my query function get's executed.

  1. function value_form(&$form, &$form_state) {
  2.  
  3. $form['cb_season'] = array(
  4. '#type' => 'select',
  5. '#title' => t('Season'),
  6. '#options' => $this->cb_season_options,
  7. );
  8.  
  9. $form['cb_year'] = array(
  10. '#type' => 'select',
  11. '#title' => t('Year'),
  12. '#options' => $this->cb_year_options,
  13. );
  14.  
  15. $form['value'] = array(
  16. '#type' => 'hidden',
  17. '#value' => '',
  18. );
  19. }

That said, I'm not sure how to get the user input for my other two form elements. When I use the devel modules dpm function to dump the contents of $this in the value_form, I only see the contents of the value form element but not the other two. The same is true when I dump the contents of the form_state variable...

I'll post back if/when I figure out how to access the values of the other form elements but I thought this might at least help others who are struggling with the same problem.

lsanderson (Thu, 07/21/2011 - 20:22)

Permalink

I'm having a similar problem. It seems that a $form['value'] form element is required in order for a value_form with 2+ elements to be submitted correctly. At least when I add a value form element (for a total of 3 form elements in one value_form) my query function get's executed.

  1. function value_form(&$form, &$form_state) {
  2.  
  3. $form['cb_season'] = array(
  4. '#type' => 'select',
  5. '#title' => t('Season'),
  6. '#options' => $this->cb_season_options,
  7. );
  8.  
  9. $form['cb_year'] = array(
  10. '#type' => 'select',
  11. '#title' => t('Year'),
  12. '#options' => $this->cb_year_options,
  13. );
  14.  
  15. $form['value'] = array(
  16. '#type' => 'hidden',
  17. '#value' => '',
  18. );
  19. }

That said, I'm not sure how to get the user input for my other two form elements. When I use the devel modules dpm function to dump the contents of $this in the value_form, I only see the contents of the value form element but not the other two. The same is true when I dump the contents of the form_state variable...

I'll post back if/when I figure out how to access the values of the other form elements but I thought this might at least help others who are struggling with the same problem.

lsanderson (Thu, 07/21/2011 - 20:29)

Permalink

Okay, after a bit more experimenting it appears that you can define a $form['value'] empty hidden form element in order to ensure the query function is executed. 

  1. function value_form(&$form, &$form_state) {
  2.  
  3. $form['cb_season'] = array(
  4. '#type' => 'select',
  5. '#title' => t('Season'),
  6. '#options' => $this->cb_season_options,
  7. //sets the default value based on the value from the options_form if this exposed form has not been submitted
  8. '#default_value' => (isset($form_state['input']['cb_season'])) ? $form_state['input']['cb_season'] : $this->options['cb_season'],
  9. );
  10.  
  11. $form['cb_year'] = array(
  12. '#type' => 'select',
  13. '#title' => t('Year'),
  14. '#options' => $this->cb_year_options,
  15. //sets the default value based on the value from the options_form if this exposed form has not been submitted
  16. '#default_value' => (isset($form_state['input']['cb_year'])) ? $form_state['input']['cb_year'] : $this->options['cb_year'],
  17. );
  18.  
  19. // required for the query function to be executed
  20. $form['value'] = array(
  21. '#type' => 'hidden',
  22. '#value' => '',
  23. );
  24. }

Then in the query function, your additional value_form form elements can be accessed using $this->view->exposed_input[

] (ie: $this->view->exposed_input['cb_year']).
  1. function query () {
  2.  
  3. // set variables to be used in modifying the query
  4. // if the user submitted the exposed form then these values will be used
  5. // otherwise the value from the options_form will be used
  6. // assumes that the name of the form element in the options_form is the same as in the values_form
  7. $cb_year = (isset($this->view->exposed_input['cb_year'])) ? $this->view->exposed_input['cb_year'] : $this->options['cb_year'];
  8. $cb_season = (isset($this->view->exposed_input['cb_season'])) ? $this->view->exposed_input['cb_season'] : $this->options['cb_season'];
  9.  
  10. // modify your query using the values submitted by the user (or the admin if user didn't apply filters) here
  11. }

Hope this helps someone!

lsanderson (Thu, 07/21/2011 - 21:00)

Permalink

in function mymodule_views_handlers()

defined

mymodule_handler_filter_view

but in function mymodule_views_data() {

there is 'handler' => 'mymodule_special_data_filter_view',

is it right? or am I missing something?

 

podarok (Tue, 08/16/2011 - 10:10)

Permalink

hey guys,

   I am getting a Error: handler for node > ms_customs_special_data doesnt exist. but I have it link to the correct class name. Im not sure what im getting, any help?

// in my ms_customs.module file

  function ms_customs_views_data() {
  $data = array();

  $data['node']['ms_customs_special_data'] = array(
    'title' => t('Custom Date filter'),
    'help' => t('Filter any views based on date ad term'),
    'filter' => array(
      'handler' => 'ms_customs_special_data_filter_view'
    ), 
  ); 
  return $data;
}

// in my ms_customs_special_data_filter_view.inc is my

class ms_customs_special_data_filter_view extends views_handler_filter

rbz (Thu, 09/08/2011 - 00:56)

Permalink

This is a great article. I am pretty much impressed with your good work. You put really very helpful information. Keep it up.

threephase filters (Tue, 12/27/2011 - 06:25)

Permalink

Hi,

thank you for you great tutorial!

Anyway I'm pretty sure there is a mistake in mymodule_views_handlers().

You declare a handler with the wrong name. It should be "mymodule_special_data_filter_view", not "mymodule_handler_filter_view".

Greetings.

-ermannob

ermannob (Fri, 02/03/2012 - 11:29)

Permalink
Views internal workings have always been kind of a secret magic for me, but your article helped me a lot! By the way, ermannob is right in mentioning that the handler key declared in hool_views_handlers() should be the same as the one in hook_views_data(). Great info, thanks.

Anilam (Tue, 10/09/2012 - 08:47)

Permalink
Hello! I've been reading your site for a while now and finally got the bravery to go ahead and give you a shout out from Dallas Tx! Just wanted to say keep up the fantastic job!

how to make pr… (Mon, 06/17/2013 - 16:16)

Permalink
Helped me a lot too. thanks.

ahdil (Wed, 09/11/2013 - 16:20)

Permalink
I am getting this error Broken/missing handler in mymodule.module
  1. function mymodule_views_api() {
  2. return array(
  3. 'api' => 2,
  4. 'path' => drupal_get_path('module', 'mymodule') . '/views',
  5. );
  6. }
mymodule.views.inc file in "views" folder
  1. function mymodule_views_handlers() {
  2. return array(
  3. 'info' => array(
  4. 'path' => drupal_get_path('module', 'mymodule') . '/views',
  5. ),
  6. 'handlers' => array(
  7. 'mymodule_handler_filter_province_multiple' => array(
  8. 'parent' => 'views_handler_filter',
  9. ),
  10. ),
  11. );
  12. }
i upload mymodule_handler_filter_province_multiple.inc file in "views" folder mymodule_handler_filter_province_multiple.inc class mymodule_handler_filter_province_mulitple extends views_handler_filter

dalvir (Thu, 12/05/2013 - 07:55)

Add new comment

The content of this field is kept private and will not be shown publicly.