How to replace the deprecated hook hook_search_api_solr_query_alter with PreQueryEvent
The hook hook_search_api_solr_query_alter (amongst others) was deprecated in search_api_solr v4.2.0 and will be removed from 4.3.0.
To replace your hook with an event, you'll need to do the following:
- Create an Event Subscriber.
- Define the Event Subscriber as a service.
- Move your code from the existing hook in to the Event Subscriber.
- Remove the hook.
Search API Solr events that can be acted on are listed in search_api_solr/src/Event/SearchApiSolrEvents.php. The example here uses const PRE_QUERY = PreQueryEvent::class; as the event that replaces hook_search_api_solr_query_alter.
1. Create an event subscriber
Create a directory structure inside your custom module: /src/EventSubscriber/
Within the newly-created EventSubscriber directory, create a new file named SolrQueryAlterEventSubscriber.php.
Inside that file, add the following:
<?php
namespace Drupal\<your_module_name>\EventSubscriber;
use Drupal\search_api_solr\Event\PreQueryEvent;
use Drupal\search_api_solr\Event\SearchApiSolrEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Alters the query where necessary to implement business logic.
*
* @package Drupal\<your_module_name>\EventSubscriber
*/
class SolrQueryAlterEventSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
return [
SearchApiSolrEvents::PRE_QUERY => 'preQuery',
];
}
/**
* {@inheritdoc}
*/
public function preQuery(PreQueryEvent $event): void {
$query = $event->getSearchApiQuery();
$solarium_query = $event->getSolariumQuery();
}
}2. Define the event subscriber as a service
Inside your custom module directory, create a <your_module_name>.services.yml file. Put the following code inside it:
services:
<your_module_name>.query_alter:
class: Drupal\<your_module_name>\EventSubscriber\SolrQueryAlterEventSubscriber
tags:
- { name: event_subscriber }4. Move your code from the existing hook to the event subscriber
Cut the code from your existing hook implementation in the .module file, and paste it within the preQuery function within the event subscriber you created in step 2.
5. Remove the hook
You can now delete the hook implementation from your .module file
6. Rebuild the cache and test
You should now rebuild the cache, either using the UI whilst logged in as an admin, or using drush cr.
Your hook implementation will no longer be used and the event subscriber should now be used in its place. Test it out by doing a search and checking your code behaves as expected.
Further reading
For more information on the Event system within Drupal core, check out the handbook page:
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion