Drupal 9.4.8. Search api solr 4.2.9
I have created a search api solr search in views
One of the fields included in this view is a custom view field: node_date_raw_field
From module hook_views_data():
$data['views']['node_date_raw_field'] = [
'title' => t('Node Date (raw)'),
'help' => t('Node Date raw field plugin.'),
'field' => [
'id' => 'node_date_raw_field',
],
'sort' => [
'field' => 'node_date_raw_field',
'id' => 'standard',
],
];
This field simply brings back the node created date field associated with the current row content datasource or file datasource. What I want to do is sort the search results of the view by this custom field using hook_views_query_alter().
None of the examples I have found so far seem to work. This below is what I have tried:
function sbn_views_query_alter(Drupal\views\ViewExecutable $view, Drupal\views\Plugin\views\query\QueryPluginBase $query) {
if ($view->id() == 'solr_search') {
# https://drupalize.me/tutorial/alter-query-used-view?p=3463
# $query->sort('node_date_raw_field', 'DESC'); // Unlike the other options, nothing shows up in sort results
# Error message: *Sorting by "node_date_raw_field" has no valid solr field*.
// Override existing Order rules.
#$query->orderby = [];
# $query->addOrderBy(NULL, NULL, 'DESC', 'node_date_raw_field');
# Simply doesn't sort.
# https://www.zyxware.com/articles/3885/drupal-how-to-use-drupal-hookview…
#$query->orderby[0] = array(
# 'field' => 'node_date_raw_field',
# 'direction' => 'desc',
#);
# Notice: Undefined property: Drupal\search_api\Plugin\views\query\SearchApiQuery::$orderby in sbn_views_query_alter()
# $query->addOrderBy(NULL, NULL, 'desc', 'node_date_raw_field');
}
}
Everything above brings back unsorted results except for $query->sort which errors out.
I checked the $query field and the field node_date_raw_field is there:
[field] => Array
(
[label] => Drupal\search_api\Plugin\views\field\SearchApiEntityField
[title] => Drupal\search_api\Plugin\views\field\SearchApiEntityField
[search_api_excerpt] => Drupal\search_api\Plugin\views\field\SearchApiStandard
[uri] => Drupal\search_api\Plugin\views\field\SearchApiEntityField
[node_label_field] => Drupal\sbn\Plugin\views\field\NodeLabelField
[node_id_field] => Drupal\sbn\Plugin\views\field\NodeIDField
[group_label_field] => Drupal\sbn\Plugin\views\field\GroupLabelField
[node_date_field] => Drupal\sbn\Plugin\views\field\NodeDateField
[node_date_raw_field] => Drupal\sbn\Plugin\views\field\NodeDateRawField
)
Also checked the class:
echo get_class($query);
Class used: Drupal\search_api\Plugin\views\query\SearchApiQuery
Is it simply not possible to sort a search api solr view by a views custom field, or am I missing something above?