Drupal Views filter - title in dropdown exposed filter

Submitted by hernani on Mon, 03/25/2013 - 10:21

I had to create a view where I could filter by title, but I wanted to be able to select from the list of all nodes available to achieve something similar to the following screenshot:

I did it creating a new filter for views. In a custom module I started by declaring the new filter in the module file:

function pcp_custom_views_data() {
  // Adds our field in the "Filters" section of Views
  $data['node']['nid2']['filter'] = array(
    'title' => t('Autocomplete nid'),
    'help' => t('Autocomplete nid'),
    'real field' => 'nid',
    'handler' => 'pcp_custom_special_data_filter_view',

  return $data;


Then pcp_custom_special_data_filter_view.inc I created the filter:

class pcp_custom_special_data_filter_view extends views_handler_filter_many_to_one
     * Shortcut to display the exposed options form.
    function value_form(&$form, &$form_state) {
        $efq = new EntityFieldQuery();
          $efq->entityCondition('entity_type', 'node')
              ->entityCondition('bundle', 'snippet')
              ->fieldCondition('field_snippet_type', 'tid', $this->view->filter['tid']->options['value'], '=');

          $results = $efq->execute();
          $entities = entity_load('node', array_keys($results['node']));

          if (!empty($entities)) {
            foreach ($entities as $entity) {
              $options[$entity->nid] = $entity->title;

          $form['value']['#type'] = 'select';
          $form['value']['#multiple'] = TRUE;
          $form['value']['#options'] = !empty($options) ? $options : array();
          $form['value']['#size'] = 5;

     * Change the query.
    function query() {
        $args = array_values($this->value);
        $this->query->add_where_expression($this->options['group'], "$this->table.$this->real_field IN (:placeholder) ", array(':placeholder' => $args),


The filter will be automatically populated with all nodes of the type node.