Рейтинг:1

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

флаг in

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

Ответить или комментировать

Большинство людей не понимают, что склонность к познанию нового открывает путь к обучению и улучшает межличностные связи. В исследованиях Элисон, например, хотя люди могли точно вспомнить, сколько вопросов было задано в их разговорах, они не чувствовали интуитивно связи между вопросами и симпатиями. В четырех исследованиях, в которых участники сами участвовали в разговорах или читали стенограммы чужих разговоров, люди, как правило, не осознавали, что задаваемый вопрос повлияет — или повлиял — на уровень дружбы между собеседниками.