Drupal - Filter a view based on current user's roles?
Following @Jimajamma's suggestion, here's what I used. I adapted his code slightly for Drupal 7 and to allow for other roles than Administrators full access to the results.
In the View, add a contextual filter on Author: Uid
, and use the following settings:
WHEN THE FILTER VALUE IS NOT AVAILABLE:
- Provide default value
- Type: PHP Code
Use the following code:
global $user;
if (
in_array('administrator', $user->roles) ||
in_array('editor', $user->roles)
)
{return -1;}
else
{return $user->uid;}
WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
- Specify validation criteria
- Validator: PHP Code
Use the following code:
if ($argument == -1)
{return FALSE;}
else
{return TRUE;}
- Action to take if filter value does not validate: Display all results for the specified field (this is what will give admins access to all results)
And that's it!
Notes:
Compared to my initial settings, the relationship (Content: Author
) isn't needed anymore; neither is the "Author" filter (which was brought in by the relationship anyway).
Apparently, for Drupal 6 the condition in the first PHP snippet should rather be if (in_array('super user', array_values($user->roles)))
.
You need to add a Contextual Filter to filter based on the currently logged in user.
- Add a contextual filter for "User: Uid"
- Select "Provide a default value"
- Choose Type: "User ID from logged in user"
You would also need to clone a new view display to show all nodes for specific roles, configured by Page Settings: Access > Role. Then choose Administrator and any other roles who should see all nodes.
You cannot OR a filter like a sort, and you would be displaying the view two different ways with filtered content and all content, so I would create two displays of this view.