0

I have an exposed filter in a view is referencing taxonomy terms from specific vocabulary. The operator allows selecting a term as the default value for that filter. What I want to achieve is to dynamically select the default value when the term weight = 0.

This should allow less privileged roles like Content Contributors to set the default value for the exposed filter by changing the order (weight) of the term without the need to edit the views settings.

I tried to research this and so far, it seems the best way to achieve this is by using (hook_views_pre_build) but I just don't know how.

2
  • I don't understand how to reproduce this or how your filters are built and what's dynamic in that.
    – leymannx
    Jan 3, 2023 at 16:53
  • @leymannx Sorry for the confusion. I've updated my question and added a screenshot for the exposed filter settings. Jan 3, 2023 at 19:16

1 Answer 1

1

After extensive search and experiment, this code worked for me:

use Drupal\taxonomy\Entity\Term;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_build().
 */

function YOUR_MODULE_NAME_views_pre_build(ViewExecutable $view) {
  if ($view->id() == 'YOUR_VIEW_ID' && $view->current_display == 'YOUR_DISPLAY_ID') {
    // Get the exposed filter for the taxonomy terms.
    $filter = $view->display_handler->getHandler('filter', 'YOUR_FILTER_ID');
    if ($filter) {
      // Query the database for taxonomy terms with a weight of 0.
      $query = \Drupal::entityQuery('taxonomy_term');
      $query->condition('weight', 0);
      $term_ids = $query->execute();
      if (!empty($term_ids)) {
        // Load the first term found with a weight of 0.
        $term = Term::load(array_shift($term_ids));
        if ($term) {
          // Set the default value for the exposed filter to the term's ID.
          $filter->options['value'] = $term->id();
        }
      }
    }
  }
}

This code will query the database for taxonomy terms with a weight of 0 when the specified view is pre-built and set the default value for the exposed filter to the ID of the first term it finds. If no terms are found with a weight of 0, it will not change the default value.

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.