0

I want to have a view which would output a node title and use a contextual filter the aliased path of a node

/nodefilter?url=/category/path-to-article

I see there no php contextual filters in drupal 8 anymore do I have to write a custom contextual filter or is there another solution ? Any help will be greatly appreciated

1

First I have created a view that uses contextual filter content ID to filter the results by "node id" and can be called like this

/nodefilter/[NID]

After I made sure the view was working I modified the content ID contextual filter adding default query paramenter named url under WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value

enter image description here

then in a custom module used the views api hook_views_pre_view as follows

use Drupal\views\ViewExecutable;
function MODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if($view->id() == 'view_machine_name'){
    $url = \Drupal::request()->query->get('url');
    $path = \Drupal::service('path.alias_manager')->getPathByAlias($url);
    if(preg_match('/node\/(\d+)/', $path, $matches)) {
      //$node = \Drupal\node\Entity\Node::load($matches[1]);
      //$nid = $matches[1];
      $args[0] = $matches[1];    
    }    
  }
}

Now the view works with NID or the url parameter

/nodefilter/[NID]
/nodefilter/?url=/category/path-to-article
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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