2

I'm using a view to populate an Entity reference field on a profile. (So it's a view of "Entity Reference" display type.)

I want to filter this view to show (and allow users to select) only:

  1. Published content (OK)
  2. Content of a certain type (OK)
  3. Only a subset of nodes available to the current user (OK)
  4. If the current user is admin or some other role, bypass the previous filter (3) and show all nodes (but still respect filters 1 and 2) (not OK)

Filters 1 and 2 are always mandatory; then either filter 3 or 4 must also be mandatory. I've tried to rearrange filters into filter groups to make this work, but I cannot find a way to build filter 4.

For filter 4, I need to filter based on the role of the current user (NOT author), and I cannot find how to do that.

I'm looking for a Relationship to bring in the current user data (something like "User: current"), and then filter on that data, but where can I find that?

3
  • The best way I've found to get the current user into a view is through the [current-user] token. Commented Sep 18, 2019 at 21:09
  • How would that work - with a filter?
    – ScottD
    Commented Sep 19, 2019 at 13:32
  • @ScottD yes, add the filter and then use the token as the fixed value. Commented Oct 1, 2019 at 0:11

1 Answer 1

0

I encountered exactly the same problem, and I ended up writing a hook for this.

I first created the basic view through the UI, and added filters 1. and 2. To filter out the elements to which the current user was not the author, I added this hook in a custom module :

function yourmodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  try {
    $userCurrent = \Drupal::currentUser();
    $uid = $userCurrent->id();
    // For non-admin users…
    if($view->id() === 'yourviewid' && !$userCurrent->hasPermission('edit any content')) {
      // …add a WHERE condition to only get the user's own nodes. This can be replaced with your own logic.
      $query->addWhere(0, 'uid', $uid);
    }
  }
  catch(Error $e) {
    drupal_set_message('The server encountered a problem. Please contact the site\'s administrator.', 'error');
    \Drupal::logger('yourmodule')->error("Error adding filter to view in yourmodule.module : %e",
      ['%e' => $e]
    );
    return;
  }
}

Hope this helps.

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.