简体   繁体   中英

How to create a role and give access to only certain users having that role to the block in moodle?

I have a block, now I want some certain users to access that block. Those certain user will have a role created for them. My question is, how to create a role, assign users to it, and that role will enable the users to see a certain block that I created.

Thanks

I would create a capability for the block in blocks/yourblockname/db/access.php

'block/yourblockname:view' => array(
    'captype' => 'read',
    'contextlevel' => CONTEXT_BLOCK,
    'archetypes' => array(
        'manager' => CAP_ALLOW
    )
)

You'll also need a language string for it in / blocks/yourblockname/lang/en/block_yourblockname.php

$string['yourblockname:view'] = 'View this block';

Then in your block class in blocks/yourblockname/block_yourblockname.php

Check the capabilitiy

function get_content() {
    ...
    $this->content = new stdClass;
    $this->content->text = '';
    $this->content->footer = '';
    ...
    if (!has_capability('block/yourblockname:view', $this->page->context)) {
        // Return blank content so the block isn't displayed.
        return $this->content;
    }

You will need to bump the version in version.php for the capability to be installed.

Then go to roles and set the capability to allow to the required role.

Here's how you can do it in moodle:

How a block can be made visible only to certain users?

1) Create your custom role from Site Administration > Users > Permissions > Define Roles

2) You can select an archetype which means selecting one them will allow you inherit that archetypes capabilities.

3) Also select the context as a block. So that you can assign this role from block settings(ie local settings) level.

4) Now go to home, turn edit on so that you can see the local block settings cog wheel on right corner of the block, click it.

5) Click assign roles to this block.

6) You are now in 'assign roles' page, see left column, under Administration you'll see Block: , and under that there are settings like: 1) Assign roles, 2) Permissions, 3) Check permissions.

7) Click on Permissions, you'll see view block under Block. There is a plus sign beneathe, click it.

8) Now you can edit who can view this block from here. Just keep the role you created and delete others.

9) Now go to 'Assign roles'.

10) You are seeing a table with Role, Description and User with role column. Click on the role name in that table.

11) You'll arrive to a page, where you have bulk assigning user to that role option. Upon assigning users to that role, you complete the process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM