Score:0

How to alter the end date views query for search api

cn flag
blu

I'm trying to alter an exposed date filter in a view I created that uses solr search api. I noticed that the end date filter doesn't work unless I add a day to the end date. so for example if i have the following nodes:

title start date end date
a 01/01/2020 01/01/2021
b 02/01/2020 02/01/2022
c 03/01/2020 03/01/2023

and i use an exposed filter to return the end date of 02/01/2022 with a less than or equal to operator it will not return nodes a and b unless i change the end date to be 02/02/2022.

I'm stuck on trying to figure out how to modify the hook_views_query_alter() to add a time(i'm assuming that's what is wrong.).

function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'my_solr_search' && !empty($view->exposed_raw_input['field_end_date'])) {
    $query->addWhere(0, 'field_end_date', $view->exposed_raw_input['field_end_date'] . '23:59', '<=');
  }
}

EDIT: This almost works, as long as there is no input in the exposed end date filter however I can't have that since the filter relies on user input:

function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'my_solr_search' && !empty($view->exposed_raw_input['field_end_date'])) {
    // Hard code the end date since there is no input.
    $end_date = DateTime::createFromFormat('m/d/Y H:i:s', $view->exposed_raw_input['field_end_date'] . ' 23:59:59');
    $group_id = $query->setWhereGroup('AND', NULL, 'where');
    $query->addWhere($group_id, 'field_end_date', $end_date->format("U"), '<=');
  }
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.