portfolio & blog

Extending Drupal Search on other User fields

The default Drupal “search by user” is performed by the hook search_execute implemented by the user module (here is the full code), which searches on the “name” field (if you can administer users it searches also on the email).
But what about searching on other fields?

As a user is an entity on Drupal 7, it can be extended with other fields, such as the first name, the last name, a biography, a city, and so on.
Let’s say we have defined these fields:

field_first_name

field_last_name

field_biography

and we want that searches can be performed also on these fields.
To do so, when using the standard Drupal search and therefore without creating indexes with the Search APIs or with Apache Solr, we can implement two hooks in our module:

The first hook adds an additional ‘People’ (or name it as you like) tab to the Drupal search page which can be enabled in admin/config/search/settings under “Active search modules” (you should uncheck the default “User” tab).
The second hook joins the field’s tables in the query and the value of these fields in the conditions of the query.

In this way a searched key can be found also inside the additional fields of the user.