Score:1

How to add view filter programmatically using hook_views_pre_view()

gb flag

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?

Score:0
cn flag

$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);

Score:0
gb flag

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,
      ];
  }
}
Score:-1
um flag

$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.

SomebodySysop avatar
gb flag
My bad. What is the command to add filter in hook_views_pre_view() in Drupal 9?
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.