Drupal 8 views set exposed filter (default) programatically with auto-submit

Setting a dynamic views exposed filter can be done via hook_form_FORM_ID_alter() regularly if it's just a prepopulation of the views exposed filter form.

But if you wish to immediately run the filters using better_exposed_filters auto-submit when the view is loaded you have to use hook hook_views_pre_build(). Otherwise setting the #default_value is just too late.

Use the following code:

  1. /**
  2.  * Implements hook_views_pre_build().
  3.  */
  4. function MYMODULE_views_pre_build(\Drupal\views\ViewExecutable $view) {
  5.   $view_ids = ['your_view_name'];
  6.   $filterValueToSet = 'myfiltervalue';
  7.   if (in_array($view->id(), $view_ids)) {
  8.     // Prevent caching may be a good idea:
  9.     \Drupal::service('page_cache_kill_switch')->trigger();
  10.     $exposedInput = $view->getExposedInput();
  11.     if (empty($exposedInput['my_exposed_filter_name'])) {
  12.       $view->setExposedInput(['my_exposed_filter_name' => $filterValueToSet]);
  13.       }
  14.     }
  15.   }
  16. }

Einordnung:

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.

More information about formatting options