8: Programatically Filter Current Nid from Views Block Listing

 

Views has a setting to exclude the current nid from the URL from the listing one is currently viewing. This is essential when you have, say, a list of related nodes that are are defined by a category that includes the current node. If you don't exclude the current node, your current node will be listed in the "related content" block on itself. Well, obviously one is related to oneself, one thinks.

First, I tired to accomplish this through the UI with these steps, below.

  • Add contextual filter:
  • Get content ID from URL:
  • Exclude results:

Perfect!

Except, wait. It's not working. Why? I have no idea.

But this works:

/**
 * Implements hook_views_query_alter
 */
function mymodule_views_query_alter($view, $query) {
  if ($view->id() == 'myview' && $view->current_display == 'mydisplay') {
    // Filter out the nid from the arg.
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $query->addWhere(0, 'nid', array((int)$node->id()), 'NOT IN');
    }
  }
}

About the Author

Hi. My name is Jeremiah John. I'm a sf/f writer and activist.

I just completed a dystopian science fiction novel. I run a website which I created that connects farms with churches, mosques, and synagogues to buy fresh vegetables directly and distribute them on a sliding scale to those in need.

In 2003, I spent six months in prison for civil disobedience while working to close the School of the Americas, converting to Christianity, as one does, while I was in the clink.