0

I added an exposed filter to my view where users can enter the desired value to filter the results accordingly. But I want to make it easier for them by changing this filter to a select box style dropdown where they can select a value out of all available values.

To make this more clear; I'm talking about a year, so each article has a field "year" and because there are many articles published in many years, I want to group all available years from all articles and show them to the user in this select box.

But I can only make this possible by adding the years in the grouped filters manually, that means each year I have to add a new option to the filter manually. And if there are articles added later which originally were published earlier than years available in the options, I probably will never cover all years in this set of static options.

So is there a way to get all years of all articles and showing them in a select box?

1 Answer 1

1

A little bit more research would have helped, I found out myself how to do this. (Though I don't know if it would work without custom code.)

I hooked into hook_form_FORM_ID_alter() inside my theme (would also work in a custom module) and altered the form like this:

function MYTHEME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-MYVIEWID-MYFORMID') {
    $nids = \Drupal::entityQuery('node')->condition('type', 'article')->execute();
    $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
    $options = ['' => 'All'];

    foreach($nodes as $nid => $node) {
      $value = $node->get('field_article_year')->getString();

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

    asort($options, SORT_NUMERIC);

    if (isset($form['article_year'])) {
      $form['article_year']['#type'] = 'select';
      $form['article_year']['#options'] = $options;
      $form['article_year']['#size'] = 1;
    }
  }
}

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.