How to Get User Group Names in Joomla 2.5

回眸只為那壹抹淺笑 提交于 2019-12-09 16:12:20

问题


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?


回答1:


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.




回答2:


Yes, this changed.

But what you should be using instead is:

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

or just getUserGroups




回答3:


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);



回答4:


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.



来源:https://stackoverflow.com/questions/10468115/how-to-get-user-group-names-in-joomla-2-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!