XF 1.5 Any way to turn user id into username?

Maester Aemon

Active member
I am in need of getting the username based on a user's UID which is used in their profile url etc. Is this possible? This is for a list to display users based on an array looking like this
Code:
["15878", "1", "10852", "13641", "9294", "662", "622", "10795", "15879", "509", "0"]
(the 0 in this case is non-existant).
 
Do I have to loop through each and every ID like this
PHP:
$user = $this->getModelFromCache('XenForo_Model_User')->getUserById($userId);

$username = $user['username'];
inside a foreach based on the array?
Is there no other way to just turn uid into username inside template editor?
 
You can do it in one query:
PHP:
$userIds = ["15878", "1", "10852", "13641", "9294", "662", "622", "10795", "15879", "509", "0"];
$users = $this->getModelFromCache('XenForo_Model_User')->getUsersByIds($userIds);
 
You can do it in one query:
PHP:
$userIds = ["15878", "1", "10852", "13641", "9294", "662", "622", "10795", "15879", "509", "0"];
$users = $this->getModelFromCache('XenForo_Model_User')->getUsersByIds($userIds);
Cool, I'll try it out. Thanks.
 
@Siropu I can't seem to get it work doing it like this
Code:
<?php

class Extra_Custom_Callbacks
{
    public static function getUsernameFromUID() {
    $userIds = ["15878", "1", "10852", "13641", "9294", "662", "622", "10795", "15879", "509", "0"];
    $users = $this->getModelFromCache('XenForo_Model_User')->getUsersByIds($userIds);
    echo $users;
    }
    }

?>
Code:
<script>
var array = [<xen:callback class="Extra_Custom_Callbacks" method="getUsernameFromUID"></xen:callback>]
</script>
Page turns blank.
 
You can't echo an array. The following code will output a JS array containing the usernames.

PHP:
<?php

class Extra_Custom_Callbacks
{
    public static function getUsernameFromUID()
    {
         $userIds = ["15878", "1", "10852", "13641", "9294", "662", "622", "10795", "15879", "509", "0"];
         $users = $this->getModelFromCache('XenForo_Model_User')->getUsersByIds($userIds);

         $usernameList = [];

         foreach ($users as $user)
         {
              $usernameList[] = $user['username'];
         }

         return '<script>var array = ' . json_encode($usernameList) . ';</script>';
   }
}
 
Back
Top Bottom