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

  • drunken monkey committed 8c217b1 on 7.x-1.x
    Issue #2502819: Fixed example code for hook_search_api_query_alter().
    
drunken monkey’s picture

Status: Active » Fixed

First off, if you know already the index is an index on users, you can do away with most of the code. Just:

  global $user;
  $query->condition('uid', $user->uid, '<>');

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!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

andrezstar’s picture

How would it be then to add a sort?
Let's say a random one... ?