1

I want to add a simple filter to an existing view in Drupal 9. It appears that I can achieve this with hook_views_pre_view(). In every example I can find, including all the "Similar questions" links that come up when entering the title of this post, I see that $view->add_item() is used. See: Add views exposed filter programmatically

However, when I try to run this code:

function sbn_views_pre_view($view, $display_id, array $args) {
  if ($view->id() == 'draft_moderation_state') {
    // Get array of draft nids
    $state = 'draft';
    $results = sbn_get_all_nodes_in_moderation_state($state);

     // There is no draft_moderation_state filter so we have to add it
      $view->add_item(
        $view->current_display,
        'filter',
        'node',
        'nid',
        array(
          'operator' => '=',
          'value' => '59',
          'group' => 1
        )
      );
  }
}

I get this error:

Call to undefined method Drupal\views\ViewExecutable::add_item()

What is the command to add filter in hook_views_pre_view() in Drupal 9?

3 Answers 3

0

I would still like to know how to add a filter using hook_views_pre_view(), but I solved my bigger problem (programmatically filtering an existing view) using

hook_views_query_alter()

function sbn_views_query_alter($view, $query) {
   if ($view->id() == 'draft_moderation_state') {    
      $field = 'node_field_data.nid';
      // Get array of draft nids
      $state = 'draft';
      $value = sbn_get_all_nodes_in_moderation_state($state);
      $operator = 'IN';
      $query->where[1]['conditions'][] = [
        "field"    => $field,
        "value"    => $value,
        "operator" => $operator,
      ];
  }
}
0

$view->setHandler() worked for me. I think this should be equivalent to the code in your question:

$nid_filter = [
  'id' => 'nid',
  'table' => 'node_field_data',
  'field' => 'nid',
  'value' => ['value' => 59],
  'operator' => '=',
];
$view->setHandler($view->current_display, 'filter', 'nid', $nid_filter);

-1

$view->add_item(...) is Drupal 7

It's Drupal 7 vs Drupal 9 issue:

it would be helpful if users of this forum would put a version of Drupal when they post questions.

1
  • My bad. What is the command to add filter in hook_views_pre_view() in Drupal 9? Nov 24, 2021 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.