Skip to content

Feature Request: Retrieving the first and short names of the user roles #353

Description

@cagriakkaya

Prerequisites

  • I am requesting the new feature to the correct repository.
  • I checked the latest version on GitHub and the README.md documentation to ensure that this functionality does not already exist.
  • I searched to make sure that this feature has not already been requested.
  • I have, or I know someone who has, the ability and willingness to test the new feature on a Moodle LMS-based site.
  • I agree to submit one feature request per issue ticket (do not submit multiple requests in one issue ticket).
  • I understand that development and support is provided by volunteer(s) and that all final implementation decisions are up TNG Consulting Inc.

Feature Request - The User Story

I wanted to extract the name and abbreviation of the role that users have, and I did it like this. I hope you'll add this in the next version.

I added this after the following line in the classes/text_filter.php directory: if (stripos($text, '{userid}') !== false) { $replace['/\{userid\}/i'] = $USER->id; } and completed my task.

I can retrieve information in the format {roleshortnames} and {roles}.

// Tag: {roles} / {roleshortnames}.
// Description: User roles in current page context (names or shortnames).
// Parameters: None.
if (stripos($text, '{roles}') !== false || stripos($text, '{roleshortnames}') !== false) {

static $rolescache = []; // Cache per (userid-contextid) for this request.
$contextid = $PAGE->context->id;
$cachekey = $USER->id . '-' . $contextid;

if (!isset($rolescache[$cachekey])) {
    $roles = get_user_roles($PAGE->context, $USER->id, true);

    $names = [];
    $shortnames = [];

    foreach ($roles as $r) {
        if (!empty($r->name)) {
            $names[] = $r->name;
        }
        if (!empty($r->shortname)) {
            $shortnames[] = $r->shortname;
        }
    }

    $names = implode(', ', array_values(array_unique(array_filter($names))));
    $shortnames = implode(', ', array_values(array_unique(array_filter($shortnames))));

    $rolescache[$cachekey] = [$names, $shortnames];
}

[$rolenames, $roleshortnames] = $rolescache[$cachekey];

if (stripos($text, '{roles}') !== false) {
    $replace['/\{roles\}/i'] = $rolenames;
}
if (stripos($text, '{roleshortnames}') !== false) {
    $replace['/\{roleshortnames\}/i'] = $roleshortnames;
}

}

Screenshots / Mock-ups

No response

Alterative you have considered

No response

Additional information

No response

Planning on submitting a solution in a pull request (PR)?

Yes

Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    question to participantDeveloper has asked a question and is waiting for a response from participant

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions