Views offers the ability to expose filters to the end user so they may filter and sort through a views listing to find what they want in a large list of content. If you have used exposed filters before you will be familiar with exposing a filter on a specific field, such as the title field, for example. But what if you want the end user to be able to search in multiple fields at the same time?
Before we dive in, if you're unfamiliar with the terminology and functionality of views in Drupal, please visit the Views module documentation.
So to create an exposed filter that can let users search multiple fields at the same time, my first thought was to create a custom module with a views_query_alter() hook that would allow me to join fields together. This is not needed, however. Views 7.x-3.x allows you to expose one filter field to the end user for multiple field searching. Views offers a 'Global: Combine filter fields' option that allows you to pick one or more fields to filter on.
In a recent use case in a website we are building we had the following issue. In the screenshot below there is an exposed filter block to the left with an exposed title filter. This field allows end users to search for a title in the view listing to the right of the exposed filter block. This field works great if the user knows the full title of the content they are looking for but in practice many of these items are referred to with a short acronym. For example, the Achievement Rewards for College content item is also known as "ARCS." When using the title search field we would like the correct content to show up even if the user searches for ARCS. To do this we need a combined filter.
The following example will assume that you know the basics of creating views in Drupal.
- The first step is to add the new combined exposed filter to your view. To do that click on the add button in the filter criteria box and wait for the overlay box to load.
- Once it has loaded type in the word 'global' into the search field at the top of the overlay window. You should be presented with at least one option.
- Select the 'Global: Combine field filter' option and click the apply button.
- Now the filter field has been added you will need to configure it to be exposed to the user as well as select the fields you wish to combine search on.
- Expose the filter to the end user by checking the exposed filter checkbox.
- Ensure you add a title for the user that is descriptive. The description field is optional.
- The operator select box provides you with several options on how the search should be performed. For this example we will use the contains option as is provides us with the most results.
- Select all of the fields that this one filter will search. Below the fields Title and Tagline are selected. You may select more then two fields.
- Click apply and save the view. That is all the configuration this view needs. Now you can create multiple search fields with custom results.