Single search box with multiple fields using Drupal Views
Searching on fields in Views is made possible by adding an exposed filter for the relevant field. You can search on multiple fields by adding multiple exposed filters. But what if you want to have one single search box searching multiple fields? This is a very common requirement.
Fortunately, you don’t need to download any additional modules, or do any view alter magic in code. All you need is the power of combined filters. I’ll illustrate this with an example.
List of users
In this example, the View has a list of users who have registered with the site and you want to allow people to search for users by their name. There are two fields for a user's name: first name and last name.
The basic View
This is how the basic view is setup. The View displays the username, first name and second name in a table. The only filter at this stage is the User: Active filter, which ensures that you only see users who are currently active.
Add the fields
Add a new filter. The filter you are looking for is called Global: Combine fields filter. You can either search for it in the Add filter criteria modal, or change the filter to global.
Select the first name and second name fields and select the exposed filter checkbox.
I’ve also changed the operator to contains any word.
Head over to the view page, and you will now see the combined filter above the results.
You can now search for either first name or second name in the single search box.
This is just a simple example. You can combine search filters for other kinds of views e.g. search for nodes using two or more fields from a specific content type.
In order to use this, the view format needs to be set to show fields. It doesn’t work if you want to display rendered entities as there are no fields to combine.
The example in this tutorial is for a Drupal 7 site. The option to add combined filters is available in Drupal 8 and it works in the same way. Beware with using the contains any word operator on Drupal 8 as it currently throws an error. There is an open issue about it on [drupal.org]. You can still use the other operators such as contains.
If you'd rather see a video walkthrough rather than reading about how to do this, check out the video below.