How to Get User Group Names in Joomla 2.5

2019-04-06 09:51发布

I'm writing a Joomla 2.5 component that I had been developing in Joomla 1.7. I have been using code like this:

$user = JFactory::getUser();
$groups = $user->get('groups');

The $groups array would contain a list of ids with the group name as the index. Joomla 2.5 seems to have scrapped this functionality. I have been unable to find out how to get the group names without directly querying the database. Is there any method for getting a list of the groups a user is a member of without having to resort to querying the database?

5条回答
贼婆χ
2楼-- · 2019-04-06 10:04

Real snippet:

            $user = JFactory::getUser();
            $db = JFactory::getDBO();

    $db->setQuery($db->getQuery(true)
        ->select('*')
        ->from("#__usergroups")
    );
    $groups=$db->loadRowList();

            $userGroups = $user->groups;
            $return=array();

          foreach ($groups as $key=>$g){
            if (array_key_exists($g[0],$userGroups)) array_push($return,$g[4]);
          }

          $groups=$return;

      /////printing groupnames for current user/////////////
         print_r($groups);
查看更多
劫难
3楼-- · 2019-04-06 10:09

Yes, this changed.

But what you should be using instead is:

JFactory::getUser()->getAuthorisedGroups();

or just getUserGroups

查看更多
劳资没心,怎么记你
4楼-- · 2019-04-06 10:19

The code I generated below gets the names of all the groups the user is a part of and stores them in the variable $groupNames separated by line breaks:

foreach ($user->groups as $groupId => $value){
    $db = JFactory::getDbo();
    $db->setQuery(
        'SELECT `title`' .
        ' FROM `#__usergroups`' .
        ' WHERE `id` = '. (int) $groupId
    );
    $groupNames .= $db->loadResult();
    $groupNames .= '<br/>';
}
print $groupNames;

It technically queries the database but is done via the Joomla API. This is working well for me on Joomla 2.5.

查看更多
贼婆χ
5楼-- · 2019-04-06 10:21

Here it is:

<?php

    $user =& JFactory::getUser();

    foreach ($user->groups as $key => $value){
        echo $key.'<br>';
    }

?>

This will print all the user group names to the screen. The user group names are the "keys" of the array $user->groups.

查看更多
老娘就宠你
6楼-- · 2019-04-06 10:22

You said " I have found that the returned array is of the form: ([0] => '1', [1] => '2') "

To fix that you need to include false as demonstrated below. Note that 43 is the userid.

jimport( 'joomla.access.access' );
$groups = JAccess::getGroupsByUser(43, false);
print_r($groups);

More detailed information can be found at http://forum.joomla.org/viewtopic.php?t=530721

Incidentally, if you're interested in a stackoverflow like QnA for Joomla please support http://area51.stackexchange.com/proposals/58842/joomla

查看更多
登录 后发表回答