1

I need an array of all usernames from a certain usergroup. How can I update my Joomla 3 component code for use in Joomla 4?

jimport( 'joomla.access.access' );
$customers = JAccess::getUsersByGroup(2);
jimport( 'joomla.user.user' );
foreach($customers as $customer){
    $user = JFactory::getUser($customer);
    $userID = $user->id;
    $arr = array();
    $arr[$userID] = $user->username;
}
$this->users = $arr;

2 Answers 2

1

The jimport statements are replaced by adding use statements prior to your class statement. The getUsersByGroup() is still valid and has no reference to being depreciated while the JFactory::getUser()/Factory::getUser() will work with Joomla 4 but is depreciated in Joomla 5.

use Joomla\CMS\Access\Access;
use Joomla\CMS\Factory;

...

$userfactory = Factory::getContainer()->get(UserFactoryInterface::class);

$customers = Access::getUsersByGroup(2);

foreach($customers as $customer)
{
    $user = $userfactory->loadUserById($customer);
     $userID = $user->id;
     $arr = array();
     $arr[$userID] = $user->username;
}

$this->users = $arr;
3
  • Do you mean to clear the array on each iteration with $arr = array();? ...we must not trust the code in questions ;) Maybe $this->users[$user->id] = $user->username; Feb 25 at 12:48
  • @Irata The code provided gives an error Exception Type: Joomla\DI\Exception\KeyNotFoundException with a message UserFactoryInterface has not been registered with the container in the stack trace. I had to add the code use Joomla\CMS\User\UserFactoryInterface; to get it to work.
    – jfischer
    Feb 25 at 18:15
  • @mickmackusa I have added your suggestion to my code.
    – jfischer
    Feb 25 at 18:19
0

You could pull this straight from the db with something like the following

$group_id = 2;

$db = \Joomla\CMS\Factory::getDbo();
$query = $db->getQuery(true);
$query->select('b.username')
    ->from($db->qn('#__user_usergroup_map', 'a'))
    ->join('INNER', $db->qn('#__users', 'b') . ' ON ' . $db->qn('a.user_id') . ' = ' . $db->qn('b.id'))
    ->where($db->qn('a.group_id') . ' = ' . $db->q($group_id));
$db->setQuery($query);
$usernames = $db->loadColumn();

// this should show the contents of the array
echo '<pre>' . print_r($usernames,1) . '</pre>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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