How do I filter search results in Drupal 8?
Actually the search module in Drupal 8 core doesn't currently display the results with the selected language.
After several searches, it is not possible to configure this in Drupal administration. There are two possible options available to us :
- Find a module that allows us to configure this
- Write a small module to modify the query generated for the search
We decided to create our module to solve this problem.
This is how we proceeded :
- Create the module named "search_results_filter_by_lang" in the modules/custom directory. For more details on creating a module in Drupal 8 go here.
Implementation of hook "hook_query_TAG_alter()" :
<?php
use Drupal\Core\Database\Query\AlterableInterface;/**
* Implements hook_query_TAG_alter()
*/
function search_results_filter_by_lang_query_search_node_search_alter(AlterableInterface $query) {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$query->condition('n.langcode', $language, '=');
}- Clear cache with the following command : drush cr
- Installation of the module
That's it, the search results are now filtered with the selected language.
Be careful that this code cancels the search by language in the advanced search. This is not a problem for us because we don't allow advanced search for visitors (disable this via /admin/people/permissions).