Hi,

I want to grab the user ID from URL, then display some text if the user is of a particular role. I am a newbie with drupal and php...please help me out.

The user of user profile is http://www.example.com/user/54
The code I am using is not giving any results

$userid = arg(1);
if ($userid->roles[3]) {
  echo "This user has role student";
}

Comments

helloanshul’s picture

Title: Restrict to user role » Display text based on role of the user profile being viewed
elvis2’s picture

$userid->roles[3] is the role ID. If you go to admin/user/roles/edit/3 you will find the Role name. In your code you will know what role name you are dealing with, and can just make a comment in your code...

<?php
$userid = arg(1);
if ($userid->roles[3]) {
  // this is the student role
// do something...
}
?>

Otherwise, you will need to query the role table, to find the role name.

$userid = arg(1);
if ($userid->roles[3]) {
  $role_name = db_result(db_query("SELECT name FROM role WHERE rid = $userid->roles[3]"));
  echo $role_name;

  // do something
}

Welcome to Drupal and good luck!

halfabrain’s picture

Hi elvis2,

I am looking for a similar solution but I cannot get this script to work. I would like to show a block only when a specific role's profile is being viewed. For instance, if a student views another student's profile page, the block is shown; but if a student views a teacher's profile page, the block isn't shown.

I entered the following into the "Show if the following PHP code returns TRUE (PHP-mode, experts only)." section:

$userid = arg(1);
if ($userid->roles[6]) {
return TRUE;
 } else {
return FALSE;
}

where [6] is the role that I wanted to show the block to. However, the block is not showing for any role's profile that I view.

Please can you guide me as to where I'm going wrong? It seems like it should be so simple and it's driving me a little crazy that I can't see where it's going wrong

Thanks

H

ressa’s picture

I use this in a block in the "Show if the following PHP code returns TRUE (PHP-mode, experts only)." section to determine if the role of the user being viewed is 'customer':

if (arg(0) == 'user' && is_numeric(arg(1)) && arg(1) > 0) { // is a user page
  $userpage = user_load(array('uid' => arg(1)));
  if (in_array('customer',$userpage->roles)) {   
    // this is a customer role being viewed
    return TRUE;
  }
}
kars-t’s picture

Status: Active » Fixed

Hi

I am closing this issue to clean up the issue queue. Feel free to reopen the issue if there is new information and the problem still resides. If not please make sure you close your issues that you don't need any more.

Maybe you can get support from the local user group. Please take a look at this list at groups.drupal.org.

Status: Fixed » Closed (fixed)
Issue tags: -PHP, -user, -roles

Automatically closed -- issue fixed for 2 weeks with no activity.