How to make a block visible only for admin and teacher in moodle?

霸气de小男生 提交于 2020-01-06 01:33:07

问题


I think there are more than one way to make block invisible for students.

1.

Hide the block

2.

Assign role to block and set permission to block

But these are done by admin by change the settings. I need a way by code. How can I write the code to make the block invisible for student.

For activity I can make invisible the activity by changing db/access.php

 'mod/questionbank:view' => array(
        'captype' => 'read',
        'contextlevel' => CONTEXT_MODULE,
        'legacy' => array(
            //'guest' => CAP_ALLOW,
            //'student' => CAP_ALLOW,
            'teacher' => CAP_ALLOW,
            'editingteacher' => CAP_ALLOW,
            'admin' => CAP_ALLOW
        )
    ),

Like this how can I make the block invisible for student by code.

EDIT

according to Davosmith's answer.

I put inside get_content function

if (!has_capability('blocks/blockname:view')) {
        return null;
        }

in blocks/blockname/block_blockname.php

and in my blocks/blockname/db/access.php contain:

'blocks/blockname:view' => array(
        'captype' => 'read',
        'contextlevel' => CONTEXT_BLOCK,
        'legacy' => array(
            //'guest' => CAP_ALLOW,
            //'student' => CAP_ALLOW,
            'teacher' => CAP_ALLOW,
           // 'editingteacher' => CAP_ALLOW,
            'manager' => CAP_ALLOW
        )
    ),

But it results in error page saying

Coding error detected, it must be fixed by a programmer: PHP catchable fatal error


回答1:


For any block, if get_contents returns null (and editing is off), the block will not be displayed.

So, put the following in the get_content function of your block (but put in a real capability that you define in db/access.php):

if (!has_capability('block/myblock:somecapability', $this->context)) {
    return null;
}


来源:https://stackoverflow.com/questions/32644417/how-to-make-a-block-visible-only-for-admin-and-teacher-in-moodle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!