I have a View that has a contextual filter that uses a token to get entity reference values on the current user to limit a view (that also points at the same reference type). If they match up, that is all the View will return in its results.

However, for Administrator roles, I do not want to apply the filter (bypass it) without duplicating the view and having different views to maintain. I tried adding the first argument of "Authored by" using the current user, and checking the role of that user in the validation. This appeared to work at first, but when a node is authored by a lower level user, the validation appears to not work (no result shows). If I change the author to another user, the node appears in the View results for that lower level user.

Without having to duplicate a View, how can I grant Administrators full access but apply the second contextual filter otherwise?

1 Answer 1


Based on a similar question I saw, I had to add this:

function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  try {
    $account = \Drupal::currentUser();
    // If user is not admin, remove the authored by argument
    if ($view->id() === 'portal' && $view->current_display == 'page_2' && !in_array('administrator', $account->getRoles())) {
      $query->where[0]["conditions"] = array_values($query->where[0]["conditions"]);
  catch(Error $e) {
    \Drupal::messenger()->addError('The server encountered a problem. Please contact the site\'s administrator.');
    \Drupal::logger('mymodule')->error("Error displaying Rate Manager: %e",
      ['%e' => $e]

This seems to support both cases, but now there is a code and argument position dependency that is not obvious from the UI. I wonder if there is a better solution?

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.