Score:1

Programmatically set a views filter value on page load (not contextual filter)

in flag

I have created some views for an Events content type with field_start and field_end timestamp fields. One of the displays is for 'Upcoming Events'.

I want to filter only those events whose start date hasn't yet passed. The way to do this with the core views date filter is to choose the 'between' operator, and enter the current timestamp as the 'min' value:

enter image description here

But I obviously want the timestamp to update dynamically on each page load. I have been trying to update the filter value programmatically, but I have not been able to.

In the my_module.module file, I played around with some ViewExecutable methods in a hook_views_pre_build() function, as follows, with no luck:

function my_module_views_pre_build(ViewExecutable $view) {

  if ($view->id()=='my_view_id') {

    $time = Drupal::time()->getCurrentTime();

    if($view->current_display=="upcoming_events_block") {
      $view->setHandlerOption("upcoming_events_block", "filter", "field_start_value", "value",
        ["min" => $time,"max" => "","value" => ""]);
    }
  }

  return $view;
}

I can see my handler options when I dump them, however they are ignored when the page loads. I tried to trigger a save:

$view->storage->save();

which also did not work.

According to the API documentation of hook_views_pre_build(), this function enables me to "Act on the view before the query is built, but after displays are attached". So this should work, right? Why doesn't it?

I tried the same with hook_views_pre_execute(), still no luck.

What is the right place to use these functions?

PS. I considered doing this with Contextual Filters but I couldn't find a way for that at all. If there is a way with Contextual Filters, I'd love some pointers!

Thanks

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.