Pre-populate Views Exposed Filter From URI

Currently in Drupal 7, it's not possible to prepopulate an exposed Views filter from a URI - at least in the UI. It is possible, but you'll need to use hook_views_pre_build().

Example Use Case

You're working with a higher-ed client, who has a search form they wish to submit to a view page to prepopulate an exposed filter. The search form is located on the site's home page. When someone submits the form, they get sent to[query goes here].

Solution - hook_views_pre_build()

The solutions is to use hook_views_pre_build(). (Don't use hook_form_alter() because it's impossible to remove the filter once on the page.)

In the example below, we're using a view with a machine name of 'my_view_title' with a display of 'block'. We're grabbing the 'search' paramter from the query string and using it as the default value for the 'title' field in the exposed filter:

 * Implements hook_views_pre_build().
function MY_MODULE_views_pre_build(&$view) {
// If a 'search' value exists from the URL's query string, then set the 'title' filter to it.
if($view->name == 'my_view_title' and $view->current_display == 'block') {
$_GET['search'])) {
$view->filter['title']->value = filter_xss($_GET['search']);

In this example, we're parsing a query value, but you could also grab various components of the path (e.g. grab the values of contextual filters). We're also running the user input through filter_xss() for security.


Thank you, very nice and clean explanation!
I was wondering, how would you code this when you want to set a value in an exposed filter list?

Chris Burge's picture

First of all, sorry for the VERY late response. (I had a spam comment problem.)

hook_views_pre_build() should work for setting the selected value in a Views exposed filter (select list). In this case, we're using a query string parameter to set the value of a select list. If you're talking about an instance where multiple selections are allowed, then I'm not sure how to pass those values to Views. You might need to use an array.

Add new comment