1

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

1 Answer 1

2

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']);
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.