I am trying to write code to create a custom filter replacing views_handler_filter_string in the code snippet below. This code would replace the text box that the default filter provides with a select box filled with values from a database table.

// The Name field
  $data['exposed']['name'] = array(
    'title' => t('Name'),
    'help' => t('The record name.'),
    'field' => array(
      'handler' => 'views_handler_field',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
  );

Please can someone point me at code that illustrates how to do this - including finding the classes that the standard filter uses. Thanks.

Comments

peterk900’s picture

Perhaps a lazy way out but I can manage to achieve almost what I want out of the box with the module Views Autocomplete Filter. Not a drop down but acceptable, and preferable if the number of selectable items is large. Here is a good video on this module.

I mean to return to this issue of creating custom filters via code and I found this post which appears to have solved the problem. However I am puzzled by the presence of the $string parameter in the callback as it does not seem to be defined elsewhere in the code (see below) and there are only two arguments in the hook_menu item. If anyone has any comments on this then please post. Thanks.

 // Name autocomplete (display only the preferred organism -in path).
  $items['tripal_ajax/nd_genotypes/genotyped_germplasm/name_to_id/%/only'] = array(
    'page callback' => 'nd_genotypes_germplasm_name_to_id_callback',
    'page arguments' => array(4, FALSE),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );


function nd_genotypes_germplasm_name_to_id_callback($organism_genus, $all_organisms, $string) {
  $matches = array();

  // custom table select
  $query = db_select('nd_genotype_germplasm', 'g')
    ->fields('g', array('name', 'genus'))
    ->condition('g.name', '%' . db_like($string) . '%', 'LIKE')
    ->condition('g.genus', $organism_genus, '=')
    ->orderBy('char_length(g.name)','ASC')
    ->orderBy('g.genus','ASC');
  $result = $query->execute();
  foreach ($result as $row) {
      $key = $row->name;
      if (!$all_organisms) {
        $matches[$key] = $row->name;
      }
      else {
        $matches[$key] = format_string(
          '@genus: @name',
          array(
            '@genus' => check_plain($row->genus),
            '@name' => check_plain($row->name),
          )
        );
      }
  }