D
D
deadnice2020-02-11 13:31:47
Drupal
deadnice, 2020-02-11 13:31:47

How to correctly set the filter when loading a view?

There is a need to programmatically call the view and add a filter to it.
It turned out to display, but the condition does not work, all elements are displayed in the view.

if ($variables["node"]->getType() == 'author') {
    $view = Views::getView('news_by_author');

    $args = array('field_author' => $variables["node"]->id());
    if (is_object($view)) {
      $view->setArguments($args);
      $view->setDisplay('page_1');
      $view->preExecute();
      $view->execute();

      $variables['author_articles'] = $view->buildRenderable('page_1', $args);
    }
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
deadnice, 2020-02-11
@deadnice

Decided like this:

if ($variables["node"]->getType() == 'author') {
    $view = Views::getView('news_by_author');

    if (is_object($view)) {
      $view->setDisplay('page_1');
      $filters = $view->display_handler->getOption('filters');
      $filters["field_author_target_id"]["value"]["value"] = $variables["node"]->id();
      $view->display_handler->overrideOption('filters', $filters);
      $view->preExecute();
      $view->execute();

      $variables['author_articles'] = $view->buildRenderable('page_1');
    }
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question