Score:1

Exposed Views Filter of Usernames in a list instead of autocomplete

kr flag

I have an exposed filter with a relationship to a reference field in my content type to users. Currently this exposed filter lets me filter by inputting a username, but its only autocomplete. Is there a way to have a select list of usernames I can pick from?

enter image description here

Score:2
eg flag

If you need a simple approach, you can install the drupal Chosen module, which does the heavy lifting.

With coding, you can use hook_form_FORM_ID_alter() as the following:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Check the views form ID.
  if ($form['#id'] != 'YOUR-VIEWS-FORM-ID') {
    return FALSE;
  }

  // Define the form options array.
  $options = [];

  // Load all user objects.
  $users = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->loadMultiple();

  foreach ($users as $user) {

    // You can add filtration here e.g.
    if ($user->hasRole('anonymous')) {
      continue;
    }
    $options[$user->id()] = $user->getDisplayName();

    $form['YOUR_FILED']['#type'] = 'select';
    $form['YOUR_FILED']['#multiple'] = FALSE;

    // Specify the empty option for our select list
    $form['YOUR_FILED']['#empty_option'] = t('Select user');

    // Add the $options from above to our select list
    $form['YOUR_FILED']['#options'] = $options;
    unset($form['YOUR_FILED']['#size']);
  }

}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.