0

I need to have a views handler for Views Search API that will allows empty (i.e. NULL) values in fields to be sorted last. For the simple views there is a solution: Views Sort Null Field but I'm totally lost, How to implement the same functionality for Views Search API?

More specifically - Views Search API provide only $query->sort() method that not allow you to add sort formula like $this->query->add_orderby(NULL, "ISNULL($this->table_alias.$this->real_field)", $this->options['order'], $alias)

| improve this question | | | | |
1

In case you are using Search API Database Search as a backend for the Search API you can solve the problem by using hook_search_api_db_query_alter hook:

/**
 * Implements hook_search_api_db_query_alter().
 *
 * Preprocesses a search's database query before it is executed.
 *
 * @param SelectQueryInterface $db_query
 *   The database query to be executed for the search. Will have "item_id" and
 *   "score" columns in its result.
 * @param SearchApiQueryInterface $query
 *   The search query that is being executed.
 *
 * @see SearchApiDbService::preQuery()
 */
function custom_module_search_api_db_query_alter(SelectQueryInterface &$db_query, SearchApiQueryInterface $query) {
  $db_query->orderby('ISNULL(field_field_name)', 'ASC');
}

This solved it and moved items with NULL values to bottom of the view. Cheers!

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.