General developer forum

How to distinct Teacher and Student in Moodle 2.x?

Picture of Кирилл Малинин
How to distinct Teacher and Student in Moodle 2.x?

First, sorry for my poor english, it's not my native language.

I`m writing a simple activity module and have one trouble - I need to distinct teacher and student. For example, let's say I have two buttons, created by simple HTML. Teacher should see bouth of them, but student should see only one button. So, I need something like that:

if (role=teacher)


   echo "<button1>";

   echo "<button2>";




   echo "<button1>";


But I don't know how to do this. Searched in Google, got a few solutions, but they don't work in my version of Moodle. And they were kinda hard to understand, I need something realy simple, because I am not even a programmer.

Thank you for answers.

Average of ratings: -
Picture of Mark Johnson
Re: How to distinct Teacher and Student in Moodle 2.x?
Core developersParticularly helpful MoodlersPlugin developers

In moodle, you don't check if a user has a particular role assigned, you check if they have a particular capability in the current context.  Read up on the Access API for an overview of how the system works.

In this case, your activity module might have the capability 'mod/foo:usebuttontwo'.

The teacher role has 'mod/foo:usebuttontwo' set to "allow", but the student role does not.  Your code then looks something like this:

$modulecontext = context_module::get_instance($cmid);
echo '<button1>';
if (has_capability('mod/foo:usebuttontwo', $modulecontext)) {
echo '<button2>';

A slightly more modern way to do this using Templates would be to pass a parameter like "showbuttontwo" to the template which is set using has_capability() as above. The template code would then look like

Average of ratings: Useful (2)