2

I am using View access per node to hide certain nodes from the general public and allow specific roles to view it, which is simple and works like a charm.

The issue is that those nodes are shown, even when browsing with anonymous user. I can't find a way for the view to identify the "View access per node" status for each row.

I thought to change my approach; I was looking through the Comparison and Overview of Access Control modules, but any non-deprecated option available in Drupal 8 seems an overkill for this case.

3
  • 1
    Views does not respect hook_node_access which is what this module uses. Module creator should've used hook_node_access_records along with hook_node_grants instead. You could do comment #3 as a workaround. – No Sssweat Nov 5 '20 at 8:26
  • 1
    Beside the Views module (which is part of Drupal core since Drupal 8), other core modules don't use hook_node_access() for a page listing entities. That's a general behavior you will find in Drupal core. – kiamlaluno Nov 5 '20 at 8:37
  • @NoSssweat it's good enough for this. Please copy your comment into an answer so I can mark it as accepted and upvote it – alotropico Nov 5 '20 at 8:39
1

Views does not respect hook_node_access which is what this module uses. Module creator should've used hook_node_access_records along with hook_node_grants instead.

You could try comment #3 as a workaround.

/**
 * Implements hook_views_pre_render().
 */
function example_views_pre_render(ViewExecutable $view) {
  $user = \Drupal::currentUser();
  $vapn_config = \Drupal::service('config.factory')->get('vapn.vapnconfig');
  $vapn_node_types = $vapn_config->get('vapn_node_list');

  foreach ($view->result as $key => $row) {
    if ($row->_entity) {
      $is_vapn_bundle = FALSE;
      if ($bundle = $row->_entity->bundle()) {
        $is_vapn_bundle = in_array($bundle, $vapn_node_types);
      }

      if (!$row->_entity->access('view', $user) && !$view->query->options['disable_sql_rewrite'] && $is_vapn_bundle) {
        unset($view->result[$key]);
      }
    }
  }
}

credit: ash2303

1
  • I'd like to clarify, for front-enders like me, that you can copy the code in your themeName.theme file, but you need to include this first: use \Drupal\views\ViewExecutable; – alotropico Nov 5 '20 at 10:21

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.