0

I created a view showing users. Then I have a list of users. I need to add a field to show the user role. I clicked add field but I don't see this field. Do I need to add a relationship to have this field available?

Update: I have Aggregation enabled.

enter image description here

  • Roles dissapear cuz of aggreagation, if u read the description on views u will see If enabled, some fields may become unavailable. – Petro Popelyshko Dec 14 '12 at 15:02
3

So you need to add 2 field into your view User uid(exclude from display) and Custom text, next go to your template.php and do next

//implement hook_preprocess_views_view_fields
function YOURTHEME_preprocess_views_view_fields(&$vars) {
    $view = $vars['view'];
    $fields = $vars['fields'];

    if ($view->name == 'usr1') { // change on your view name
        $results = $view->result;
        $roles = array();
        foreach ($results as $row) {
            $user = user_load($row->uid);
            $roles = implode(', ',$user->roles ); //get all user roles
            //check if user name from field equal to current user in array
            if ($fields['name']->raw === $row->users_name) { 
                $fields['nothing']->content = $roles;//put that roles to custom text field
            }
        }
    }
}

THIS CODE NEED IMPROVEMENTS, cuz it iteracts on every field of your view, so you can work on this :D.

  • thanks, but I don't get it. Do you mind to elaborate on this, please – chefnelone Dec 14 '12 at 15:33
  • ok wait a bit, gonna post example here – Petro Popelyshko Dec 14 '12 at 15:35
  • I can't get it working, no errors, just not working. – chefnelone Dec 17 '12 at 11:08
  • are you sure u use proper view name if ($view->name == 'usr1') { and use dpm for debug to see what is wrong, maybe some names may differ from mine, like this -> $fields['name'] or $field['nothing'] – Petro Popelyshko Dec 17 '12 at 11:57
1

Try to disable Aggreegation, enable the Role field and then enable again the Aggreegation.

Notice that the Role field is a multi-value one (Roles is a list).

So if I understand well you should better use a module like https://www.drupal.org/project/views_aggregator.

0

There should be User:Roles available in field list.

  • I agree. But look at the capture I uploaded at the bottom of my question – chefnelone Dec 14 '12 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.