Drupal Views exposed filter of Author name as a drop down

后端 未结 5 1141
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 04:02

This is a follow up question to Drupal Views exposed filter of Author name. The following question was answered and works. I can filter a view by user name. The user name is

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 04:30

    You'll need a custom module for that.

    I've done this for Drupal 7 this way: create a module, say, views_more_filters, so you have a views_more_filters.info file like this:

    name = Views More Filters
    description = Additional filters for Views.
    core = 7.x
    
    files[] = views_more_filters_handler_filter_author_select.inc
    files[] = views_more_filters.views.inc
    

    (file views_more_filters_handler_filter_author_select.inc will contain our filter handler).

    A basic views_more_filters.module file:

     3);
    }
    

    Then define your filter in views_more_filters.views.inc:

     array(
          'author_select' => array(
            'group' => t('Content'),
            'title' => t('Author UID (select list)'),
            'help' => t('Filter by author, choosing from dropdown list.'),
            'filter' => array('handler' => 'views_more_filters_handler_filter_author_select'),
            'real field' => 'uid',
          )
        )
      );
    }
    

    Note that we set author_select as a machine name of the filter, defined filter handler ('handler' => 'views_more_filters_handler_filter_author_select') and a field we will filter by ('real field' => 'uid').

    Now we need to implement our filter handler. As our filter functions just like default views_handler_filter_in_operator, we simply extend its class in views_more_filters_handler_filter_author_select.inc file:

    value_options if someone expects it.
       */
      function get_value_options() {
        $users_list = entity_load('user');
    
        foreach ($users_list as $user) {
          $users[$user->uid] = $user->name;
        }
    
        // We don't need Guest user here, so remove it.
        unset($users[0]);
    
        // Sort by username.
        natsort($users);
    
        $this->value_options = $users;
    
        return $users;
      }
    }
    

    We haven't had to do much here: just populate options array with a list of our users, the rest is handled by parent class.

    For further info see:

    • Views API
    • Where can I learn about how to create a custom exposed filter for Views 3 and D7? on Drupal Answers
    • Demystifying Views API - A developer's guide to integrating with Views
    • Sophisticated Views filters, part2 - writing custom filter handler (in Russian, link to Google translator)
    • Tutorial: Creating Custom Filters in Views

提交回复
热议问题