Group names as Views exposed filter select list - Drupal 8

Drupal has gotten so much more powerful and easy to work with, but there are still a few things that are missing that seem like they should be a given. Such as, the ability to format certain Views exposed filters, like node titles or Group names, as dropdown select lists rather than an empty textfield that requires the user to know what the possible options might be instead of presenting them.

Here's how to format a Views exposed filter of Group titles as a select list populated with the names of your groups. I was able to do this following this example of a theme function which formats node title exposed filters as selects.

First you'll need to add a field to your View with the Group titles, then add an exposed filter on that field. It will show up as a textfield, but adding the following code to your .theme file will turn it into a nice select list. You will of course need to replace the placeholders in ALLCAPS with the appropriate values. The 'FILTERNAME' value can be found in the "filter identifier" field in the exposed filter settings in the View.

function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-FORM-ID') {

    $gids = \Drupal::entityQuery('group')->condition('type','GROUPTYPE')->execute();
    $groups = \Drupal\group\Entity\Group::loadMultiple($gids);
    $options = ['' => 'All'];

    foreach($groups as $gid => $group) {
      $value = $group->get('label')->getString();

      if (isset($value)) {
        $options[$value] = $value;
      }
    }

  // find the "FILTERNAME" in the "filter identifier" field in the exposed filter settings
    if (isset($form['FILTERNAME'])) {
      $form['FILTERNAME']['#type'] = 'select';
      $form['FILTERNAME']['#options'] = $options;
      $form['FILTERNAME']['#size'] = 1;
    }
  }
}

Tags:

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.