get_roleid of the user

get_roleid of the user

by Thea Ganoe -
Number of replies: 3
In a course/lib.php file add on, I need to know if a user is a student.

I did it like this:

$r = get_record('role_assignments', 'userid', $USER->id);

//echo 'role' . $r->roleid;

Is there a global variable that holds the roleid (so I don't have to query the mdl_role_assignments table) ?




Average of ratings: -
In reply to Thea Ganoe

Re: get_roleid of the user

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
That is almost certainly the wrong question to be asking.

The roles and capabilities system is designed so that code is written in terms of capabilities. So your code should look like

if (has_capability('somthing', $coursecontext)) {
/// Do something.
}

Doing things this way gives administrators full flexibility when defining roles.

You code will not work. One user may have many roles assignments, for example in different courses.
In reply to Tim Hunt

Re: get_roleid of the user

by Thea Ganoe -
Well I knew it was wrong, but it worked, so that's why I was asking. I'll review the roles and capabilities, (honestly I haven't quite got the hang of what exactly is a course context yet) !

Thanks for your help,

Thea




In reply to Thea Ganoe

Re: get_roleid of the user

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
A context is just a fancy name for part of Moodle site.

It might be the whole Moodle site. That is the relevant context for administrator-y thinks like adding users or changing the configuration.

Or it might be a course category, or a course, or an individual activity. So, as you can see, the categories contain each other. A course will be inside one or more categories, and the whole site; and it will contain activities. Another way of saying the same thing is that the contexts form a tree structure.


If you like Object-Oriented Programming, then another way to thing about this is to think of the Context as the base class, which is responsible for being part of the tree and managing permission checking; and then the different parts of Moodle like CourseCategory, Course, Activity, and so on, are subclasses. (And to carry the anology further, different types of activity, like ForumActivity, QuizActivity, and so on, are subclasses of the general Activity.)

Of course, Moodle does not use the PHP class/object syntax for these things, so in the PHP code, they don't look like objects, but in a higher level, vague sense, you can choose to think of it like that.