Member-only story

How to Set a Default Value for an Exposed Filter In a View In Drupal

Using hook_views_pre_build

Sergio Guardiola Herrador
1 min readDec 1, 2024
Photo by Dan Gold on Unsplash

Sometimes, you want to set a default value on an exposed filter in a view. It’s not yet possible to do it directly in the view, which I think should be implemented in the Views module in the future, but for now, we can use hook_views_pre_build to achieve this.

In this example, for view id content and display page_1, I’m setting a default value for exposed filter langcode_1. This will be applied only if langcode_1 doesn’t have any value yet (replace custom_module with your module name):

/**
* Implements hook_views_pre_build().
*/
function custom_module_views_pre_build(ViewExecutable $view) {
// Set exposed filter default value to "All" in /admin/content.
if ($view->id() == 'content' && $view->current_display == 'page_1') {
$exposed_input = $view->getExposedInput();
// Check if langcode_1 is not set, then set it to the default "All".
if (empty($exposed_input['langcode_1'])) {
$exposed_input['langcode_1'] = 'All';
$view->setExposedInput($exposed_input);
}
}
}

👉 Find out more about me here: https://sergioguardiola.net 🔥

--

--

Sergio Guardiola Herrador
Sergio Guardiola Herrador

Written by Sergio Guardiola Herrador

I write articles in English and Spanish, mostly about programming, technology, travel, money, investing. You can find me here: https://sergioguardiola.net

No responses yet