How to make a block visible only for admin and tea

2019-08-12 09:06发布

问题:

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;
}