drupal-viewsdrupal-9

How can I dynamically change the default value for views exposed filter referencing taxonomy terms when the term weight value = 0


I have an exposed filter in a view is referencing taxonomy terms from specific vocabulary. The operator (screenshot below) 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.


Solution

  • 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.