DEV Community

Elise Gaetz Ferguson for Epicosity

Posted on • Originally published at Medium on

Multi parameter search in Craft CMS

The challenge  — an attorney search feature that would search by any or all of the following:

  • Attorney Name
  • Attorney Practice Area (category)
  • Keyword

Populate the Category Dropdown

The first step is building the search form. We just need to add the additional fields to the typical Craft CMS search form. In this example we have a section on the site for Practice Areas. Each entry is a different practice area and we can populate a drop down field with the titles for each of these Practice Area entries.

Practice Area Field populated by Practice Area section of site

The keyword field is simply the default search field and the Attorney Name field is and additional basic text field.

Keywords and Attorney Name Search Fields

Set the Search Parameters

In typical fashion a user enters their search parameters and clicks the search button.

What actually happens is that the Craft CMS form builds a URL with the search parameters that were entered in the form and it comes out looking something like this:

Extract the Parameters from the URL

Get all the parameters from the URL

Using the handy dandy public method we can get those search terms out of the URL query string.

Build a Search Query with these Parameters

Build an array containing all search parameters

We want to check that each parameter is defined before we merge it into our main queryParams variable. Craft CMS uses “AND” by default for multiple search parameters so all of our parameters will be included in the search.

We also decided display the search parameters back to the user’s screen.

Display the user’s search parameters

We can then run the search, using the Craft CMS pagniation to display the results. In this specific case we also check for an additional parameter of “sectionHandle” which is only defined if we are using the Attorney Search feature to search withing the Attorneys section. We can use this same search template when conducting a regular site search. In that case we won’t have the sectionHandle defined and we will search the whole site.

Using the search parameter array, run the search (with pagination)

Finally Display the Search Results

Now we can display the search results in whatever layout we choose, similar to the default Craft CMS search results.

Display the search results

Top comments (0)