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 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.
GROUPTYPE is the machine name of your group type, which is the human-readable name lowercased and spaces replaced with underscores. If, for example, your group type is Client, GROUPTYPE will be client; if it's Book Club, it will be book_club. (You should be able to leave the group type condition statement out if the view is showing all group types).
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;
}
}
}
Comments
How do you find the value for GROUPTYPE?
Great question. Grouptype is the machine name of your group type, so the name lowercased and spaces replaced with underscores. If you have a group type "Client", grouptype would be "client"; if it's, say, "Awesome Groups", it would be awesome_groups. I'll add that to the post.
When I try to dump an exposed form ID it was always the same, views_exposed_form
We/You should use like this, right?
https://gist.github.com/jez500/4d1ef061e41f69a964732461cb0ec43a
Hi Istvan, it's been a while since I've looked at this, but yes, it does make sense if the form ID is always the same, to check for the specific view name first.