Add Autocomplete Search Results to Text Fields in Drupal

Search is an important function in almost every site. There is a simple feature which we can implement to improve user experience, and that is ‘search autocomplete’.

Autocomplete means ‘predictive text’, and it is a feature in which the system predicts the rest of a word a user is typing.

It provides suggestions of words to users while typing, and speeds up the human-computer interaction. It can work well particularly in search because the list of suggested words will come directly from controlled keywords from the system itself.

It is also helpful in situations where long words or hard-to-spell terminologies are involved.

In this tutorial, we’ll learn how to install and configure the Search Autocomplete module in Drupal. The module provides an easy way to convert any text field into an autocomplete field.

Getting Started

Let’s begin by first downloading the Search Autocomplete module using Composer.

composer require drupal/search_autocomplete

Then go and install the module.

Patch Module

As of the writing of this article, if you’re using Drupal 9.2 and up, you’ll need to patch the module. If you installed the module and the autocomplete isn’t working, look for JavaScript errors. If you get the following errors:

Then you’ll need to apply the patch from this issue.

Follow the steps below to patch the module when you’re using Composer.

1. Download the Composer patches package:

composer require cweagans/composer-patches

2. Open composer.json and add the patch into the “extra” area.

"extra": {
        "patches": {
            "drupal/search_autocomplete": {
                "value.autocomplete is not a function - https://www.drupal.org/i/3220334": "https://www.drupal.org/files/issues/2021-06-24/value-autocomplete-not-function-3220334-3.patch"
            }
        },
    }

3. Then remove and re-add the Search autocomplete module.

composer remove drupal/search_autocomplete && composer require drupal/search_autocomplete

Composer should tell you that the patch is applied.

Search Autocomplete Configuration

To configure the module, go to Configuration > Search and metadata > Search Autocomplete settings:

And you will reach this configuration page:

There are 3 configuration settings by default, each applies to a specific area of search in the system. The list of autocomplete results to be displayed is actually powered by views configuration, which comes with the module by default. They can be found in the following figure.

Each of these 3 ‘views’ configuration settings match to its corresponding ‘search autocomplete’ configurations, and the following table shows the matching pairs.

Search Autocomplete Configuration

Corresponding Views Configuration Setting

Type of Search applied

Search Block

Words Autocompletion Callbacks

Search of indexed words

Search Form (content tab)

Nodes Autocompletion Callbacks

Search of nodes

Search Form (users tab)

Users Autocompletion Callbacks

Search of users

The configuration of each ‘Search Autocomplete Setting’ are grouped into 3 parts: How, What and Advanced:

1. HOW – HOW TO DISPLAY SEARCH AUTOCOMPLETE SUGGESTIONS?

The settings are self-explanatory, and we shall not go into details to repeat the explanations. Basically, it governs how the autocomplete results are displayed.

The minimum keyword size is 3 by default. It should probably match to the ‘Minimum word length to index’ of the Drupal system under ‘search pages’ configuration (separate). The default value ‘3’ is good for English language but may be considered different if other languages are used.

It is recommended to keep the default settings to start with.

2. WHAT – WHAT TO DISPLAY IN SEARCH AUTOCOMPLETE SUGGESTIONS?

The first entry ‘autocomplete suggestions’ matches the corresponding views configuration settings. This setting seems untraditional. Fortunately this is an autocomplete entry. By typing “autocomplete” in this entry, a list of all possible entries will be shown for selection.

It is recommended to keep everything by default.

3. ADVANCED – ADVANCED OPTIONS

This is an advanced option. Don’t use this option unless you know what to do with it. It is recommended to leave it untouched.

For the configuration of the views setting, we shall not go into detail here. However, by modifying carefully from the default views, we can tune the search results.

How It Works

By default, this “Search Autocomplete” module works with Search in Drupal. With the 3 default configurations, it works with search of words, nodes or users. As described in the beginning of this article, when users enter the keywords in the search fields, it will list matching results in a list automatically.

In fact, there are more this module can do, and that relates to the next section of Advanced Configuration.

Advanced Configuration

The module integrates with the default 3 types of search in Drupal core. However, this module actually adds autocomplete functionalities to virtually any simple text fields in the Drupal site. That means new configurations to the ‘search autocomplete’ module is necessary. It will be too complicated to go through this in detail here, but we shall try to give some guidance.

First, enable the option “Use autocompletion helper tool for Search Autocomplete administrators.”

Go to the search field which requires autocomplete, and hover over the search field with the mouse. A dialog will appear with the option to “add autocompletion”. Click on this option.

A series of dialog will automatically appear and guide you through the above configurations. A new views setting for this entry might be needed, which can be simply started by duplicating one of the 3 default views settings.

This autocomplete feature can even be applied to input form of a content type. As mentioned, we shall not go into details in this.

Creat Custom Autocompletion Configuration

Now that we understand how it all works, let’s create our own custom configuration.

Let’s assume that we have a custom content type called Directory (you can call it whatever you want) and we’ll create a view with an exposed filter that can be used to filter by title. We’ll add autocomplete functionality to the exposed title field.

If you want to learn more about Views, check out our “Getting started with Views” tutorial.

Create View

We need to create a basic view to display Directory content items.

1. Go to Structure, Views (admin/structure/views) and click on “+ Add view”.

2. Fill out the “Add new view” form, using the values defined in Table 1.0 and click on “Save and edit”.

Table 1.0. Create a new view.

Options

Value

View name

Directory search

Machine name

directory_search

Show

Content of type Directory Sorted by Newest first

Create a page

Checked

3. Click on Add in the “Filter criteria” section.

Search for title and add the filter to the view.

4. Select Contains from the Operator drop-down and check the “Expose this filter to visitors…” checkbox, then click on Apply.

You should see the exposed filter in the preview section below the views configuration.

If you go to /directory-search you should see the title as an exposed filter.

Duplicate Search Autocomplete Views

As mentioned above, views is used to display the autocomplete results.

We only want the autocomplete to return directory items not all content. We’ll need to duplicate the “Nodes Autocompletion Callbacks” view and add a single filter.

1. From the Views page (admin/structure/views), find “Nodes Autocompletion Callbacks” and click on the Duplicate button.

2. Change the View name to “Directory Autocompletion Callbacks” and click on Duplicate.

3. Click on Add in the “Filter criteria” section and search for “Content type” and click on “Add…”.

4. Check Directory from “Content types” and click on Apply.

5. We need to change the path on this duplicated view. Click on Advanced, then “/callback/nodes”.

And change the path to “/callback/directory”.

Then save the view.

Create Autocompletion Configuration

The final piece to the puzzle is to create an “Autocompletion Configuration” for the view.

1. Go to Configuration, “Search Autocomplete settings” (admin/config/search/search_autocomplete) and click on “Add new Autocompletion Configuration”.

2. Add “Directory search page” into “Human readable name” and click on “Create…”.

NOTE: Leave the “ID selector this configuration should apply to” empty for now.

3. In the “What” section, search for “Directory Autocompletion” in the autocomplete field. This is the view we just duplicated.

4. Now we need to give the module an element ID to add the autocomplete functionality. Go to the view and inspect the HTML and here is how I would target it.

The ID selector would then be “#views-exposed-form-directory-search-page-1 #edit-title”.

Once everything has been done click on Update.

Test View

Go to the Directory search page (/directory-search) and if everything was configured correctly the autocomplete should work.

Summary

This Search Autocomplete module enhances user experience in the search blocks and search forms. It’s helpful where users are searching for long or hard-to-spell keywords or unfamiliar terminologies.

By tuning the views configuration, we can customize search experience with controlled keywords or terminologies with increased accuracy and priorities.

This module also works for the input form of content types. As an example, it can be applied to simple text fields which reference other entities in the systems when creating new nodes.

In those applications where search is important and requires these special criteria, this module is useful.

FAQs

Q: I installed the module and nothing works.

If you’re running Drupal 9.2 and up you’ll need to patch the module. Follow the instructions in the “Getting Started” section.

Q: I duplicated the “Nodes Autocompletion Callbacks” view but I can still see other content.

Make sure you change the Path under “Advanced”.

10 thoughts on “Add Autocomplete Search Results to Text Fields in Drupal”

  1. Hey there,
    great article, perfectly explained. Thank you!
    I do have a question, though…
    Is there a way to search in more than one field simultaneously? Say product name, manufacturer name, and body text?
    Thanks again and cheers!
    Thilo

  2. form id is changing for authenticated and anonymous users.
    ID for login user: search-form-block–2
    anonymous user: search-form-block
    so search autocomplete not working for anonymous user. kindly help on this

    1. Hi,

      Drupal adds the “–2” to element IDs if the ID appears more than once.

      Do you have multiple search forms on the page for logged in users? Try and use the same search form for both anonymous and authenticated users.

      1. Used for both login and anonymous users. but issue only in anonymous users. so search in second form not working. some times after cache refreshment, search form is working. how can i use same form in both topbar and banner section? please visit the site https://www.inxinternational.com/

  3. Hi ji, How can i add node meta description field along with title and body content for auto search.

    1. Just customise the callback view. And adjust the view fields accordingly. You’ll only be able to add view fields.

      Look at the “Duplicate Search Autocomplete Views” section.

Leave a Comment

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.