Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Apress.Pro.Drupal.7.Development.3rd.Edition.Dec.2010.pdf
Скачиваний:
73
Добавлен:
14.03.2016
Размер:
12.64 Mб
Скачать

C H A P T E R 1 3

■ ■ ■

Searching and Indexing Content

Drupal’s search module provides a feature-rich solution that meets the needs of most web sites. When the core search module doesn’t provide the features and functionality you need for your site, you can expand on the core module through the Search API. In this chapter, I’ll discuss how modules can hook into the search API and build custom search forms. We will also look at how Drupal parses and indexes content and how you can hook into the indexer.

Tip Drupal understands complicated search queries containing Boolean AND/OR operators, exact phrases, or even negative words. An example of all these in action is as follows: Beatles OR "John Lennon" –insect. In this example, we are searching for all occurrences of the word Beatles or the phrase John Lennon, where the results do not contain the word insect.

Building a Custom Search Page

Drupal has the ability to search nodes and usernames out of the box. Even when you develop your own custom node types, Drupal’s search system indexes the content that’s rendered to the node view. For example, suppose you have a recipe node type with the fields ingredients and instructions, and you create a new recipe node whose node ID is 22. As long as those fields are viewable by the administrator when you visit http://example.com/?q=node/22, the search module will index the recipe node and its additional metadata during the next cron run.

While it would appear at first glance that node searching and user searching would use the same underlying mechanism, they’re actually two separate ways of extending search functionality. Rather than querying the node table directly for every search, node searching uses the help of an indexer to process the content ahead of time in a structured format. When a node search is performed, the structured data is queried, yielding noticeably faster and more accurate results. We’ll get to know the indexer later in this chapter.

307

CHAPTER 13 SEARCHING AND INDEXING CONTENT

Username searches are not nearly as complex, because usernames are a single field in the database that the search query checks. Also, usernames are not allowed to contain HTML, so there’s no need to use the HTML indexer. Instead, you can query the users table directly with just a few lines of code.

In both of the preceding cases, Drupal’s search module delegates the actual search to the appropriate module. The simple username search can be found in the user_search_execute() function of modules/user/user.module, while the more complex node search is performed by node_search_execute() in modules/node/node.module. The important point here is that the search module orchestrates the search but delegates the implementation to the modules that know the searchable content best.

The Default Search Form

You’ll be glad to know the search API has a default search form ready to use (see Figure 13-1). If that interface works for your needs, then all you need to do is write the logic that finds the hits for the search requested. This search logic is usually a query to the database.

Figure 13-1. The default user interface for searching with the search API

While it appears simple, the default content search form is actually wired up to query against all the visible elements of the node content of your site. This means a node’s title, body, additional custom attributes, comments, and taxonomy terms are searched from this interface.

The Advanced Search Form

The advanced search feature, shown in Figure 13-2, is yet another way to filter search results. It expands on the basic search form by providing the ability to select the content types to restrict the search to and an easy-to-use interface for entering words, phrases, and negative search words.

308

CHAPTER 13 SEARCHING AND INDEXING CONTENT

Figure 13-2. The advanced search options provided by the default search form

The default search form can be changed by implementing the search hook in a module, then using hook_form_alter() on the form ID search_form (see Chapter 11) to provide an interface for the user. In Figure 13-2, both of these are happening. The node module is implementing the search hook to make nodes searchable (see the node_search functions in modules/node/node.module) and is extending the form to provide an interface (see node_form_search_form_alter() in -modules/node/node.module).

Adding to the Search Form

Let’s look at an example. Suppose we are using path.module and want to enable searching of URL aliases on our site. We’ll write a short module that will implement Drupal's search hooks to make the aliases searchable and provide an additional tab in Drupal’s search interface.

Introducing the Search Hooks

There are several hook_search functions that your module may use in Drupal 7.

hook_search_info(): This function allows a module to tell the search module that it wishes to perform searches on content it defines (custom node types, users, or comments for example) when a site search is performed. The values set in this function define the tab that appears at the top of the search form for the type of content your module searches (e.g., Content, Users, Comments) and the path value appended after ‘/search’ in the url (e.g., /search/node).

hook_search_execute($keys = NULL): This function executes a search for a set of keywords that are entered by the user, and passed to the function as a string.

hook_search_reset(): This function is called when the search index is going to be rebuilt. This function is used by modules that also implement hook_update_index(). If your module keeps track of how much of its content is indexed, you’ll want to use this function to reset the module’s counters in preparation for reindexing.

309

Download from Wow! eBook <www.wowebook.com>

CHAPTER 13 SEARCHING AND INDEXING CONTENT

hook_search_status(): This function reports the status of reindexing the content in the database. It returns a value of the total number of items to index and the number of items left to index.

hook_search_access(): This function allows a module to define permissions for a search tab. If the user does not have the proper permissions, then the tab will not be displayed on the search form.

hook_search_admin(): This function adds elements to the search settings form.

Formatting Search Results with hook_search_page()

If you have written a module that provides search results, you might want to take over the look and feel of the results page by implementing hook_search_page(). If you do not implement this hook, the results will be formatted by a call to theme_search_results($variables), which has its default implementation in modules/search/search-results.tpl.php. Do not confuse this with theme_search_result($variables), which formats a single search result and has its default implementation in modules/search/searchresult.tpl.php.

Making Path Aliases Searchable

Let’s begin our example. We’ll be implementing a search option that allows site visitors to paths by implementing several search hooks.

Note For the following examples to work, you’ll need to have the path module enabled and some paths assigned to nodes (so there is something to search). You’ll also need to rebuild your search index data before testing these examples. You can do so by selecting Administer -> Site configuration -> Search settings, clicking the “Re-index site” button, and then visiting Administer -> Reports -> Status report to run cron manually. The search module does indexing when cron runs.

Create a new folder named pathfinder at sites/all/modules/custom, and create the files shown in Listings 13-1 and 13-2 with the new directory.

Listing 13-1. pathfinder.info

name = Pathfinder

description = Gives administrators the ability to search URL aliases. package = Pro Drupal Development

core = 7.x

dependencies[] = path

files[] = pathfinder.module

310

CHAPTER 13 SEARCHING AND INDEXING CONTENT

Listing 13-2. pathfinder.module

<?php

/**

*@file

*Search interface for URL aliases.

*/

Leave pathfinder.module open in your text editor; you’ll continue to work with it. The next function to implement is hook_search_info(). This hook places the tab at the top of the search form for our search of URL aliases.

/**

* Implements hook_search_info() */

function pathfinder_search_info() { return array(

'title' => 'URL Aliases',

);

}

The next function checks to see if the person has the correct permissions to search URL aliases.

/**

* Implements hook_search_access(). */

function pathfinder_search_access() {

return user_access('administer url aliases');

}

And finally we’ll use the hook_search_execute() function to perform the search and return the results.

/**

* Implements hook_search_execute(). */

function pathfinder_search_execute($keys = NULL) { $find = array();

$query = db_select('url_alias')->extend('PagerDefault'); $query->fields('url_alias', array('source', 'alias')); $query->condition('alias', '%' . db_like($keys) . '%', 'LIKE'); $result = $query

->limit(15) ->execute();

311

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]