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 https://example.com/academics/programs?search=[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:
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.
Comments
Pieter (not verified)
Tue, 04/25/2017 - 14:41
Permalink
exposed list filter
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
Tue, 01/22/2019 - 14:19
Permalink
Select List vs Multiple Select List?
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