Score:0

How can I dynamically change the default value for views exposed filter based on the terms weight?

mh flag

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.

leymannx avatar
ne flag
I don't understand how to reproduce this or how your filters are built and what's dynamic in that.
Fareed Fattal avatar
mh flag
@leymannx Sorry for the confusion. I've updated my question and added a screenshot for the exposed filter settings.
Score:1
mh flag

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.

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.