Abstract Light
Stock Image

User Based Views Filters in Drupal 7

One common task on the iToysoldiers site was making stuff visible to a user either because it was created by that user or because it was not. Case in point: Each player has a dashboard. That dashboard shows them all sorts of things. One of those things is a list of all the folks who've commented on their posts.

Now, I don't think the players need to be informed that they, themselves, have commented on a particular post. I'm of the opinion that this clutters the display with something that the player already knows. So what I had to do was create a view that showed all comments on nodes authored by the current logged in user. That was pretty easy. Just add an Author UID contextual filter with the default value set to "current logged in user". Easy peasy.

That particular view shows all comments. In order to strip out all the comments made by the current user I used a php filter with this code:

global $user;
if ($user->uid == $row->uid) {
return TRUE;
} else {
return FALSE;
}

You can use the first part of the If statement to compare the current user's ID to any value. In the above case I have the comment author's UID field excluded and I use that in the PHP code. I didn't have to do it that way but it makes it easier to see and edit the code if I can display it's output for troubleshooting (and possibly other stuff).

Here's a similar bit of code for panel access. It also lets the Admin user look at the page:

if ($contexts['argument_entity_id:node_1']->data->uid == $contexts['logged-in-user']->data->uid || $contexts['logged-in-user']->data->uid == 1) {
return TRUE;
} else {
return FALSE;
}

Could I do this a different way? Sure I could. Just like vi, ask two drupal people how to best accomplish a task and you'll get three answers. *snicker. Restricting or granting access based upon a user's relationship to the author of the content is pretty handy. I kinda wish it was built in but this works.

Note: This is one of my older blog posts.  Drupal 7 is still out there so it might help folks. Of course, at this point I'd recommend you take a gander at Drupal 9.

This article was updated on March 11, 2021

Rob Tacey

Rob is the IT Systems Manager for a manufacturing automation company in Southwestern Ontario. It's great. He's a technologist focusing on information technology, IT security, and customer satisfaction. With over 20 years of experience in various IT roles, it might actually be worth reading some of his stuff.

Comments