Display username in flexible_table

Display username in flexible_table

by Andy Smith -
Number of replies: 1

I have decided to display usernames instead of first names and last names. To do that I changed the fullnameformat string to $a->username. Everything turned out to be fine except for one thing. The tables are rendered incorrectly. The names are displayed as {$a->username}, but all the links work correctly. Here is the picture of what is happening.


I need to edit the col_fullname($row) function so that it displays the username instead of real names (I don't need real ones anywhere). I found out that I am able to display the user IDs by editing the last line:

 return html_writer::link($profileurl, $name);

to

 return html_writer::link($profileurl, $userid);

I tried to include $DB and added the lines

$username = $DB->get_record('user', array('id' => $userid), 'username');

 return html_writer::link($profileurl, $username);

This resulted in an error:

Object of class stdClass could not be converted to string

So, the question is: how can I edit this function to get usernames?

Using moodle 3.6.2.

Average of ratings: -
In reply to Andy Smith

Re: Display username in flexible_table

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

The result of calling:

$username = $DB->get_record('user', array('id' => $userid), 'username');

Is an object with just a single member variable: $username->username

If you just want to retrieve the username directly, then you can do:

$username = $DB->get_field('user', 'username', ['id' => $userid]);

However, if you are doing this for each user, then this will result in a lot of extra database calls, which can add a large overhead to your page.

Ideally, you should be loading all the usernames at once, to avoid this overhead.