Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
I am following the example code for hook_search_api_alter(). I have a search index of users, and I want to exclude the logged-in user from the search results. I am using the following code:
/**
* Implements hook_search_api_query_alter()
*/
function MYMODULE_search_api_query_alter($query) {
global $user;
if ($query->getIndex()->getEntityType()) {
$info = entity_get_info($query->getIndex()->getEntityType());
$query->condition($info['entity keys']['id'], $user->uid, '!=');
}
}
However, although the condition is !=, when I check my search view, only the currently logged-in user is shown. I tried changing the operator to = and I also get the same result.
When I use dpm(), I see that $user->uid is set correctly (to the currently logged-in user).
How can I exclude the currently logged-in user from the search results?
Comments
Comment #2
drunken monkeyFirst off, if you know already the index is an index on users, you can do away with most of the code. Just:
The main thing, though, is that the example was actually wrong there – thanks a lot for pointing this out!
The correct operator is <>, not !=. Since the latter operator doesn't exist, the backend (Solr, I'd guess?) seems to fall back to the "default" = operator, explaining the unexpected behavior.
I've now fixed the example code. Thanks again!
Comment #4
andrezstar CreditAttribution: andrezstar commentedHow would it be then to add a sort?
Let's say a random one... ?